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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can we use any other parameter name or variable name (declared in our code outside of the query) instead of a & b which represent the current XElement ?
@Shailesh: Yes, you can use other variables. The variables will be captured by the lambda expressions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.