我有一个LINQ查询,因为存储结果的变量将用于" if"声明,我必须在查询之前初始化它。这需要创建一个类,因为列表中存储了不同的数据类型 - 但是我在LINQ查询中制作类成员时遇到了麻烦,我不确定原因。
类别:
public class OtherProgramType
{
public string State { get; set; }
public string PrgName { get; set; }
public short? ProgramTypeID { get; set; }
public string DisplayText { get; set; }
}
代码:
List<OtherProgramType> otherPrograms;
otherPrograms = (from hm in db.HabitatManagement
join svy in db.Survey on hm.SurveyID equals svy.SurveyID
join iu in db.InventoryUsers on hm.UserID equals iu.UserID
join pt in db.ProgramType on hm.ProgramTypeID equals pt.ProgramTypeID
where pt.Program != "State Agency Public Land Programs"
&& pt.Program != "State Agency Private Land Programs"
&& svy.ReportingYear == (from svy in db.Survey
where svy.ReportingYear.HasValue
select svy.ReportingYear.Value).Max()
|| pt.Program != "State Agency Public Land Programs"
&& pt.Program != "State Agency Private Land Programs"
&& svy.ReportingYear == (from svy in db.Survey
where svy.ReportingYear.HasValue
select svy.ReportingYear.Value).Max() - 1
select new
{
iu.StateID,
hm.ProgramTypeID,
pt.Program
})
.Distinct()
.Select(x => new OtherProgramType { x.StateID, x.Program, x.ProgramTypeID, DisplayText = x.StateID.ToString() + ", " + x.Program.ToString() })
.OrderBy(x => x.StateID)
.ToList();
这是我想要新类成员的行:
.Select(x => new OtherProgramType { x.StateID, x.Program, x.ProgramTypeID, DisplayText = x.StateID.ToString() + ", " + x.Program.ToString() })
x.StateID, x.Program, x.ProgramTypeID
在红色曲线中加下划线,并且表示&#34;无效的初始化成员声明符。&#34;
答案 0 :(得分:1)
您需要说明字段分配,特别是因为x
中的字段与您的类型OtherProgramType
.Select(x => new OtherProgramType
{
State = x.StateID,
PrgName = x.Program,
ProgramTypeID = x.ProgramTypeID,
DisplayText = x.StateID.ToString() + ", " + x.Program.ToString()
})
答案 1 :(得分:1)
您需要提供要分配给的属性的名称:
.Select(x => new OtherProgramType {
State = x.StateID,
PrgName = x.Program,
ProgramTypeID = x.ProgramTypeID,
DisplayText = x.StateID.ToString() + ", " + x.Program.ToString()
})
答案 2 :(得分:1)
以上答案都绝对正确。只是添加:
如果你的类有一个构造函数来获取你的代码可能的所有参数:
public class OtherProgramType
{
public OtherProgramType(string s, string pn, short? ptid, string dt)
{
this.State = s;
this.PrgName = pn;
this.ProgramTypeID = ptid;
this.DisplayText = dt;
}
public string State { get; set; }
public string PrgName { get; set; }
public short? ProgramTypeID { get; set; }
public string DisplayText { get; set; }
}
现在适当的行可能是:
...
.Select(x => new OtherProgramType ( x.StateID, x.Program, x.ProgramTypeID, x.StateID.ToString() + ", " + x.Program.ToString() ))
...
请注意()
而不是{}
。