I know IEnumerable has been discussed several times here but I couldn’t find the answer to my specific question so I’m bringing it up as a new question.
Consider the following piece of code:
static void Main(string[] args)
{
List<string> testList = new List<string> {"Test", "Test1", "Test1"};
IEnumerable<string> filtered = testList.Where(x => x == "Test1");
DoSomeWork(filtered);
DoSomeMoreWork(filtered);
}
public static void DoSomeWork(IEnumerable<string> items)
{
foreach (var item in items)
{
Console.WriteLine("do some work");
}
}
public static void DoSomeMoreWork(IEnumerable<string> items)
{
foreach (var item in items)
{
Console.WriteLine("do some more work");
}
}
Am I right, that this causes not only the two items in “filtered” to iterate two times but actually the items in “testList”? So, considering that “testList” was a big list with 10000 items and “filtered” reduces it to 10 items, it would be more clever to make “filtered” a list (aka use var and just append ToList() at the end)
EDIT:
That’s the most embarrassing question I ever asked here. I knew it would be bad to iterate an IQueryable for example because this would result in fetching the data twice from the DB. However I wasn’t exactly sure about in memory lists. I would delete the question if I could 😉
List is ultimatly inherit from IEnumrable check this
One more thing you can create list of IEnurable using the following constructor avaialble
EDIT
The derivedi.e filtered list is get iterated twice by the both methods but append .ToList() method at the end .
http://msdn.microsoft.com/en-us/library/fkbw11z0.aspx