tags:

views:

33

answers:

2

Hi,

I am writing a LINQ query which has a sort of subquery. It looks like this:

        var x = from p in pc
                let Cntrs = p.GetCounters().Where(args => args.CounterName == CounterName)
                select Cntrs;

Cntrs is a PerformanceCounter object. However, the intellisense returns it as a collection with collection methods.

I don't see the properties such as NextValue, etc (which is what I want).

What am I missing? Also, and I know this must have been asked before, what's the difference between the let and into keywords?

Thanks

A: 

This means that the Where method is returning more than one instance, in other words you have more than one counter whose name equals the value of your CounterName variable.

If you don't care which one you get you can use the FirstOrDefault extension method to retrieve the first item from the sequence that is being returned from the Where like this:

var x = from p in pc
        let Cntrs = p.GetCounters()
                     .Where(args => args.CounterName == CounterName)
                     .FirstOrDefault()
        select Cntrs;
Andrew Hare
Actually the Where() returns IENumerable. I used Take() to get 1 counter but that didn't work.
dotnetdev
var x = from p in pc let Cntrs = p.GetCounters().Where(args => args.CounterName == CounterName).Take(1) select Cntrs.ElementAt(1);That works, but if I take 1 (as above) then I don't want to be using ElementAt, when there is only one item.
dotnetdev
Ah yes, first or default is perfect. Thanks!
dotnetdev
A: 

Don't use the var keyword, and the mystery will be resolved.

x is an IEnumerable<PerformanceCounter>


Also, and I know this must have been asked before, what's the difference between the let and into keywords?

The keyword let introduces a new query variable into scope.

from c in Customer
let firstOrder = c.Orders.First()
select new {c, firstOrder}

The keyword into introduces a new query variable into scope and removes all previous query variables from scope.

from c in Customer
select new {c.Name, c.Orders} into smallerCustomer
select smallerCustomer.Name

c is not in scope in that last select clause.

from c in Customer
group c by c.Name[0] into g
select g.First()
David B