Invalid anonymous type member declarator in LINQ

折月煮酒 提交于 2021-02-07 05:21:24

问题


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

The details of the two entities is something like:

students { id, name}

subjects { studentID, subjectName, passed}

where "passed" is of boolean type.

Now I want to query the student name and count of subject that he can pass with follows:

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

But i get error msg:Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

I dun know how to solve it. Would anyone help me please? thanks


回答1:


This means that you need to name your anonymous type's properties that cannot be inferred

select new 
{
    s.name, 
    Count=s.subjects.Count(i => i.passed.Equals(true))
};

Usually, the property name is good enough, however you are using the Count method, so that property has no inherent name




回答2:


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 (...)



来源:https://stackoverflow.com/questions/15841035/invalid-anonymous-type-member-declarator-in-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!