Invalid anonymous type member declarator in LINQ

前端 未结 2 652
旧巷少年郎
旧巷少年郎 2021-02-19 22:45

I have two entities. One is \"Students\" while another is \"Subjects\".

The details of the two entities is something like:

students { id, name}

subject         


        
2条回答
  •  情话喂你
    2021-02-19 23:05

    You have to add anonymous type properties names:

    var result = from s in db.students 
                 select new {
                     s.name,
                     count = s.subjects.Count(i => i.passed.Equals(true)
                 };
    

    You can skip them only when using member assignment. Compiler will take the name from that member. That's why s.name can be applied without specifying property name. Count() is an expression, so you have to specify how the property should be named.

    Source: Anonymous Types (C# Programming Guide)

    If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them. You must provide a name for a property that is being initialized with an expression (...)

提交回复
热议问题