C# 使用字典上的linq join更新列表属性
我有一个自定义列表和字典C# 使用字典上的linq join更新列表属性,c#,.net,linq,C#,.net,Linq,我有一个自定义列表和字典 class HldSS { string ID string IDLong string Name // other fields } class SecurityID { string ID1 string ID2 string IDLong } 我的名单是 List<HldSS> 结果 hldList ID IDLong ABC
class HldSS
{
string ID
string IDLong
string Name
// other fields
}
class SecurityID
{
string ID1
string ID2
string IDLong
}
我的名单是
List<HldSS>
结果
hldList
ID IDLong
ABC ABC123
ABC ABC123
LMN LMN456
PLO
ABC ABC123
通常,如果LINQ查询不应该更新某些内容,则必须创建一个新列表
var query = from hld in hldList
join dic in dicID
on hld.ID equals dic.Key
select new HldSS
{
ID = hld.ID,
IDLong = dic.Value.IDLong,
Name = hld.Name,
// other properties
};
List<HldSS> res = query.ToList();
这也比LINQ查询更高效。LINQ查询不应该更新某些内容,您想(重新)创建列表吗?啊,是的,这听起来确实不错。是,只要保留hldList中的所有记录,重新创建列表就可以工作
hldList dicID
ID IDLong ID1 IDLong
ABC ABC ABC123
ABC LMN LMN456
LMN
PLO
ABC
hldList
ID IDLong
ABC ABC123
ABC ABC123
LMN LMN456
PLO
ABC ABC123
var query = from hld in hldList
join dic in dicID
on hld.ID equals dic.Key
select new HldSS
{
ID = hld.ID,
IDLong = dic.Value.IDLong,
Name = hld.Name,
// other properties
};
List<HldSS> res = query.ToList();
foreach(HldSS h in hldList)
{
SecurityID sec;
if(dic.TryGetValue(h.ID, out sec))
h.IDLong = sec.IDLong;
}