When i use a standard Extension Method on a List such as
Where(…)
the result is always IEnumerable, and when
you decide to do a list operation such as Foreach()
we need to Cast(not pretty) or use a ToList() extension method that
(maybe) uses a new List that consumes more memory (is that right?):
List<string> myList=new List<string>(){//some data};
(Edit: this cast on’t Work)
myList.Where(p=>p.Length>5).Tolist().Foreach(...);
or
(myList.Where(p=>p.Length>5) as List<string>).Foreach(...);
Which is better code or is there a third way?
Edit:
Foreach is a sample, Replace that with BinarySerach
myList.Where(p=>p.Length>5).Tolist().Binarysearch(...)
The
asis definitely not a good approach, and I’d be surprised if it works.In terms of what is “best”, I would propose
foreachinstead ofForEach:If you desperately want to use list methods, perhaps:
or indeed
but note that this does (unlike the first) require an additional copy of the data, which could be a pain if there are 100,000 items in
myListwith length above 5.The reason that LINQ returns
IEnumerable<T>is that this (LINQ-to-Objects) is designed to be composable and streaming, which is not possible if you go to a list. For example, a combination of a fewwhere/selectetc should not strictly need to create lots of intermediate lists (and indeed, LINQ doesn’t).This is even more important when you consider that not all sequences are bounded; there are infinite sequences, for example:
as until the
ToListit is composing iterators, not generating an intermediate list. There are a few buffered operations, though, likeOrderBy, which need to read all the data first. Most LINQ operations are streaming.