我的Linq查询是。
string spouseName="jenny";
var empData = from sData in EmpList
from member in sData.familyNames
where string.Compare(member, spouseName, true) == 0
select new Employee
{
CompanyDept = sData.company,
EmpName = sData.empName,
FamilyNames.Add(spouse) //ERROR HERE Not able to access as list
};
此处empList为List<Employee>
class Employee
{
private string companyDept
private string empName
private List<string> _familyNames = new List<string>();
public string CompanyDept
{
get { return companyDept}
set { companyDept= value; }
}
public string EmpName
{
get { return empName}
set { empName= value; }
}
public List<string> FamilyNames
{
get { return _familyNames }
set { _familyNames = value; }
}
}
问题:
这里我试图获得Employee
类型的linq输出...但列表familyNames只包含一个项目配偶名称,而不是所有家庭成员的列表。??
但我在familyList收到错误。无法将项目添加到familyNames列表中以无法分配。
需要帮助,为什么会出现错误或者我错在某处?
答案 0 :(得分:6)
正确的翻译是:
select new Employee
{
CompanyDept = sData.company,
EmpName = sData.empName,
FamilyNames = { spouse } // 'nested' collection-initializer
};
原因是您只需要Add
上的FamilyMember
来电,而不是新列表的完整属性重新分配,这就是FamilyNames = new List<string> { spouse }
做。
松散地说,这转化为:
var temp = new Employee();
temp.CompanyDept = sData.company;
temp.EmpName = sData.empName;
temp.FamilyNames.Add(spouse);
return temp; // this is selected.
答案 1 :(得分:3)
您需要自己初始化列表。变化:
FamilyNames.Add(spouse)
要:
FamilyNames = new List<string>(new []{ spouse })
答案 2 :(得分:3)
应该是
select new Employee
{
CompanyDept = sData.company,
EmpName = sData.empName,
// FamilyNames.Add(spouse) //ERROR HERE Not able to access as list
FamilyNames = new List<string> {spouse}
} ;
虽然我原本期望sData.spouse
或member.spouse