I got the following LINQ Expression:
Context.TableOne.Select(
one =>
new
{
one.Column1,
one.Column2,
one.Column3,
one.Column4,
one.Column5,
one.Column6,
one.Column7,
one.Column8,
one.Column9,
TwoCount = one.TableTwo.Count()
});
When I select it as this:
Context.TableOne.Select(
one =>
new
{
One = one,
TwoCount = one.TableTwo.Count()
});
I would have gotten a nested property “One” containing all the fields of “one”. This would require me (for example in a datagrid) to specify the FieldNames One.Column1 or One.Column2 instead of Column1 or Column2
Is it possible to include the TwoCount = one.TableTwo.Count()-Statement without needing to specify each and every column in this expression?
When you use
new {....}you are creating a new anonymous type. You are then setting the properties on that type with the object initializer syntax. It may be easier to understand if we break this down to what is actually happening.First you are creating a new type
Foo. Let’s simplify this to 3 propertiesNow, let’s just look at the lambda expression that is your select. We can extract this to a function like below.
As you can see, we must set each property. We could encapsulate this logic in a constructor or somewhere else in class
Foobecause it is not an anonymous type. However, with an anonymous type, there isn’t must you can do.