I know that IEnumerable has been discussed several times here, but I could not find the answer to my specific question, so I raise it as a new question.
Consider the following code snippet:
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"); } }
I am right that this leads to the fact that two elements in the "filtered" are repeated twice, but actually the elements in the "testList"? So, given that "testList" was a large list with 10,000 elements, and the "filtered" reduced it to 10 elements, it would be smarter to "filter" the list (otherwise use var and just add ToList () at the end)
EDIT: This is the most embarrassing question I have ever asked. I knew that it would be bad to repeat IQueryable, for example, because it would result in retrieving the data twice from the database. However, I was not exactly sure about the memory lists. I would delete the question if I can ;-)
source share