开发者

Confusion over storing a type in a temp variable in a LINQ query

开发者 https://www.devze.com 2022-12-13 13:49 出处:网络
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)

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 (whic开发者_StackOverflowh 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


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;


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

精彩评论

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