开发者

Explanation of this LINQ expression

开发者 https://www.devze.com 2023-04-06 11:22 出处:网络
I would be grateful if someone could explain this following LINQ expression: Endpoint adapter = (from adap in this

I would be grateful if someone could explain this following LINQ expression:

Endpoint adapter = (from adap in this
                    where
                        (endpointName == DEFAULT_ENDPOINT_NAME && adap.IsDefault) ||
                        (endpointName != DEFAULT_ENDPOINT_NAME && adap.Name == endpointName)
                    select adap).FirstOrDefault();

I can pretty开发者_Go百科 much get the gist of this, I just need help with the from adap in this section. I would've expected this would be selecting from the current class - but I can't find anything within the current class that's a collection. Could you point me to where the data is likely to be coming from, adap?


The class the code resides in implements IEnumerable<T> or IQueryable<T> as that is needed for it be to able to call the IEnumerable.Where or IQueryable.Where method.


This is a query expression. The C# compiler basically translates it to:

Endpoint adapter = this.Where(adap => (endpointName == DEFAULT_ENDPOINT_NAME && 
                                       adap.IsDefault) ||
                                      (endpointName != DEFAULT_ENDPOINT_NAME &&
                                       adap.Name == endpointName))
                       .FirstOrDefault();

It's likely (but not required) that Where is an extension method call - probably Enumerable.Where or Queryable.Where. If you could show us the declaration of the type this call resides in, it would make it clearer.

Basically once you've applied the "pre-processor" step, it should be clearer what's going on. In particular, if you type:

this.Where

into Visual Studio and hover over "Where", what does it show?

EDIT: Now we know that you're deriving from List<Endpoint> (which I'd frankly advise against, to be honest - favour composition over inheritance; deriving from List<T> is almost always a bad idea), it's really calling Enumerable.Where.


Your class implements IEnumerable<T> so you can select from this I would say.

0

精彩评论

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