开发者

Explain the below Linq Query?

results.Where(x=>x.Members.Any(y=>members.Contains(y开发者_如何学编程.Name.ToLower())

I happened to see this query in internet. Can anyone explain this query please.

suggest me a good LINQ tutorial for this newbie.

thank you all.

Edited:

what is this x and y stands for?


  • x is a single result, of the type of the elements in the results sequence.
  • y is a single member, of the type of the elements in the x.Members sequence.

These are lambda expressions (x => x.whatever) that were introduced into the language with C# 3, where x is the input, and the right side (x.whatever) is the output (in this particular usage scenario).

An easier example

var list = new List<int> { 1, 2, 3 };
var oddNumbers = list.Where(i => i % 2 != 0);

Here, i is a single int item that is an input into the expression. i % 2 != 0 is a boolean expression evaluating whether the input is even or odd. The entire expression (i => i % 2 != 0) is a predicate, a Func<int, bool>, where the input is an integer and the output is a boolean. Follow? As you iterate over the query oddNumbers, each element in the list sequence is evaluated against the predicate. Those that pass then become part of your output.

foreach (var item in oddNumbers)
    Console.WriteLine(item);

// writes 1, 3


Its a lambda expression. Here is a great LINQ tutorial


Interesting query, but I don't like it.

I'll answer your second question first. x and y are parameters to the lambda methods that are defined in the calls to Where() and Any(). You could easy change the names to be more meaningful:

results.Where(result => 
    result.Members.Any(member => members.Contains(member.Name.ToLower());

And to answer your first question, this query will return each item in results where the Members collection has at least one item that is also contained in the Members collection as a lower case string.

The logic there doesn't make a whole lot of sense to me with knowing what the Members collection is or what it holds.


x will be every instance of the results collection. The query uses lambda syntax, so x=>x.somemember means "invoke somemember on each x passed in. Where is an extension method for IEnumerables that expects a function that will take an argument and return a boolean. Lambda syntax creates delegates under the covers, but is far more expressive for carrying out certain types of operation (and saves a lot of typing).

Without knowing the type of objects held in the results collection (results will be something that implements IEnumerable), it is hard to know exactly what the code above will do. But an educated guess is that it will check all the members of all the x's in the above collection, and return you an IEnumerable of only those that have members with all lower-case names.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜