views:

161

answers:

1

I am new to LINQ to XML in .net(C#, asp.net). I want to know more about Lambda expressions. I am using Lambada expression with the following query.

count = FieldRoot.Element("USER").Element("MM")
            .Descendants("MMMS")
            .Where(a => a.Attribute("ID").Value == MID)
            .SelectMany(b => b.Descendants("ABC")).Count();

Can you please tell me how the Lambda expression work specially in case of parameters (in the above case a & b) ? What is the basic concept of parameters in Lambda expression ? Can we use the names of the variables defined outside of the query instead of a & b ? which elements a & b represent in the above case represent ? Can we pass parameters from outside in the query ? If we can pass parameters from outside query then how it will be done? If you give me any other example instead of the above query to understand the concept of parameter in Lambda expression then it will also help me a lot.

+1  A: 

The basic concept is that you're calling Where on a sequence of XElement values - so the lambda expression is executed several times, with a value for a as the "current" XElement. The lambda expression then says whether or not that XElement should be included in the results.

For the SelectMany call, this is effectively flattening a sequence of sequences - from one XElement, you're yielding a sequence of all the ABC descendant elements.

This is really just LINQ to Objects - it's just that LINQ to XML fits in very neatly with LINQ to Objects.

Jon Skeet
Shailesh Jaiswal
@Shailesh: Yes, you can use other variables. The variables will be captured by the lambda expressions.
Jon Skeet