gpt4 book ai didi

c# - 使用 LINQ 将一个列表中的值分配给另一个列表

转载 作者:太空狗 更新时间:2023-10-29 20:51:48 25 4
gpt4 key购买 nike

您好,我在将一个列表项的属性值分配给另一个列表项时遇到了一点问题。我知道我可以通过遍历两个列表等“旧方法”来解决它,但我正在寻找使用 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 });

我想实现以下目标:

  • destinationList 填写sourceList中相应条目的名称(按Id)
  • destinationList 不应包含未同时出现在两个列表中的条目(例如,应删除 Id: 4,5)- 类似于 inner join
  • 我想避免使用更新的条目创建新的 destinationList,因为这两个列表都已经存在并且非常大,所以没有“转换”或“选择新”。

最后 destinationList 应该包含:

1 "1111"
2 "2222"
3 "3333"

是否有某种使用 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);

关于c# - 使用 LINQ 将一个列表中的值分配给另一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9708266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com