使用LINQ将值从一个列表分配给另一个列表
您好我将一个列表项的属性值分配给其他人有一点问题。 我知道我可以通过迭代两个列表来解决它“旧方法”但我正在寻找使用LINQ的更优雅的解决方案。
让我们从代码开始……
class SourceType { public int Id; public string Name; // other properties } class DestinationType { public int Id; public string Name; // other properties } List sourceList = new List(); 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 destinationList = new List(); 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应该包含:
1 "1111" 2 "2222" 3 "3333"
使用LINQ是否有某种优雅(一线Lambda?)解决方案?
任何帮助将不胜感激! 谢谢!
我只是建立一个字典并使用它:
Dictionary 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);
除非“避免创建新的目标列表”的最后要求,这应该工作
var newList = destinationList.Join(sourceList, d => d.Id, s => s.Id, (d, s) => s);
为了避免“避免创建新的目标列表”,可以使用下面的内容,这与通过整个列表循环没有任何不同,除了它可能不那么详细。
destinationList.ForEach(d => { var si = sourceList .Where(s => s.Id == d.Id) .FirstOrDefault(); d.Name = si != null ? si.Name : ""; }); destinationList.RemoveAll(d => string.IsNullOrEmpty(d.Name));
希望这将是你想要的结果。 首先根据键(Id)连接两个列表,然后从sourceList设置属性值。
var result = destinationList.Join(sourceList, d => d.Id, s => s.Id, (d, s) => { d.Name = s.Name; return d; }).ToList();
坦率地说,这是最简单的:
var dictionary = sourceList.ToDictionary(x => x.Id, x => x.Name); foreach(var item in desitnationList) { if(dictionary.ContainsKey(item.Id)) { item.Name = dictionary[item.Id]; } } destinationList = destinationList.Where(x => x.Name != null).ToList();
你可以做一些丑陋的Join
但我不会打扰。
我希望这对你有用。 最后,destinationList具有正确的数据,而不创建任何类型的新列表。
上述就是C#学习教程:使用LINQ将值从一个列表分配给另一个列表分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
destinationList.ForEach(x => { SourceType newSource = sourceList.Find(s=>s.Id == x.Id); if (newSource == null) { destinationList.Remove(destinationList.Find(d => d.Id == x.Id)); } else { x.Name = newSource.Name; } });
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1001521.html