use*_*810 6 .net c# linq lambda list
您好我将一个列表项中的属性值分配给其他人有一点问题.我知道我可以通过迭代两个列表来解决它"旧方式"但我正在寻找使用LINQ的更优雅的解决方案.
让我们从代码开始......
class SourceType
{
    public int Id;
    public string Name;
    // other properties
}
class DestinationType
{
    public int Id;
    public string Name;
    // other properties
}
List<SourceType> sourceList = new List<SourceType>();
sourceList.Add(new SourceType { Id = 1, Name = "1111" });
sourceList.Add(new SourceType { Id = 2, Name = "2222" });
sourceList.Add(new SourceType { Id = 3, Name = "3333" });
sourceList.Add(new SourceType { Id = 5, Name = "5555" });
List<DestinationType> destinationList = new List<DestinationType>();
destinationList.Add(new DestinationType { Id = 1, Name = null });
destinationList.Add(new DestinationType { Id = 2, Name = null });
destinationList.Add(new DestinationType { Id = 3, Name = null });
destinationList.Add(new DestinationType { Id = 4, Name = null });
Run Code Online (Sandbox Code Playgroud)
我想实现以下目标:
最终destinationList应该包含:
1 "1111"
2 "2222"
3 "3333"
Run Code Online (Sandbox Code Playgroud)
使用LINQ是否有某种优雅(一线Lambda?)解决方案?
任何帮助将不胜感激!谢谢!
我只是建立一个字典并使用它:
Dictionary<int, string> map = sourceList.ToDictionary(x => x.Id, x => x.Name);
foreach (var item in destinationList)
    if (map.ContainsKey(item.Id))
        item.Name = map[item.Id];
destinationList.RemoveAll(x=> x.Name == null);
Run Code Online (Sandbox Code Playgroud)
        希望这会达到您想要的结果。首先基于key(Id)加入两个列表,然后从sourceList设置属性值。
        var result = destinationList.Join(sourceList, d => d.Id, s => s.Id, (d, s) =>
        {
            d.Name = s.Name;
            return d;
        }).ToList();
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           30344 次  |  
        
|   最近记录:  |