简体   繁体   中英

What it the easiest way to make LINQ to process all collection at once?

I often have similar constructions:

var t = from i in Enumerable.Range(0,5)
        select num(i);

Console.WriteLine(t.Count());
foreach (var item in t)
    Console.WriteLine(item);

In this case LINQ will evaluate num() function twice for each element (one for Count() and one for output). So after such LINQ calls I have to declare new vatiable: var t2 = t.ToList();

Is there a better way to do this?

You can call ToList without making a separate variable:

var t = Enumerable.Range(0,5).Select(num).ToList();

EDIT : Or,

var t = Enumerable.Range(0,5).Select(x => num(x)).ToList();

Or even

var t = (from i in Enumerable.Range(0,5)
         select num).ToList();

I usually call the functions so it could look like this:

var t = Enumerable.Range(0,5).Select(x=>num(x)).ToList();

...

var count = 0
foreach(var item in t)
{
   Console.WriteLine(item)
   count++;
}

num is now evaluated once per item. If you wanted to use the predicate overload (Count(i=>i.PropA == "abc")) then just wrap the increment in an if. Don't use extension methods for everything; like you realized, just because you can't see the implementation doesn't mean it isn't still costing you.

If you expect to use the concrete values a lot, then ToList() is a great answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM