Poma
Poma

Reputation: 8484

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?

Upvotes: 0

Views: 121

Answers (3)

SLaks
SLaks

Reputation: 887777

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();

Upvotes: 4

KeithS
KeithS

Reputation: 71573

...

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.

Upvotes: 1

Ken Henderson
Ken Henderson

Reputation: 2828

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

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

Upvotes: 1

Related Questions