开发者

Should I use a simple foreach or Linq when collecting data out of a collection

For a simple case, where class foo has a member i, and I have a collection of foos, say IEnumerable<Foo> foos, and I want to end up with a collection of foo's member i, say Li开发者_JAVA技巧st<TypeOfi> result.

Question: is it preferable to use a foreach (Option 1 below) or some form of Linq (Option 2 below) or some other method. Or, perhaps, it it not even worth concerning myself with (just choose my personal preference).

Option 1:

foreach (Foo foo in foos)
    result.Add(foo.i);

Option 2:

result.AddRange(foos.Select(foo => foo.i));

To me, Option 2 looks cleaner, but I'm wondering if Linq is too heavy handed for something that can achieved with such a simple foreach loop.

Looking for all opinions and suggestions.


I prefer the second option over the first. However, unless there is a reason to pre-create the List<T> and use AddRange, I would avoid it. Personally, I would use:

 List<TypeOfi> results = foos.Select(f => f.i).ToList();

In addition, I would not necessarily even use ToList() unless you actually need a true List<T>, or need to force the execution to be immediate instead of deferred. If you just need the collection of "i" values to iterate, I would simply use:

 var results = foos.Select(f => f.i);


I definitely prefer the second. It is far more declarative and easier to understand (to me, at least).

LINQ is here to make our lives more declarative so I would hardly consider it heavy handed even in cases as seemingly "trivial" as this.

As Reed said, though, you could improve the quality by using:

var result = foos.Select(f => f.i).ToList();

As long as there is no data already in the result collection.


LINQ isn't heavy handed in any way, both the foreach and the linq code do about the same, the foreach in the second case is just hidden away.

It really is just a matter of preference, at least concerning linq to objects. If your source collection is a linq to entities query or something different, it is a complete different case - the second case would put the query into the database which is much more effective. In this simple case, the difference probably won't be that much, but if you throw in a Where operator or others into it and make the query non-trivial, the linq query will most likely have better/faster performance.


I think you could also just do

foos.Select(foo => foo.i).ToList<TypeOfi>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜