[英]How to combine two lists<Class> without duplicates in one of variables
我有两个清单:
public class ListTemplate
{
public decimal Id { get; set; }
public string Title { get; set; }
}
public List<ListTemplate> List1 = new List<ListTemplate>();
public List<ListTemplate> List2 = new List<ListTemplate>();
清单1:
ID = 1, Title = "a"
ID = 2, Title = "b"
ID = 3, Title = "c"
ID = 4, Title = "d"
清单2:
ID = 3, Title = "c"
ID = 4, Title = "ab"
ID = 5, Title = "a"
ID = 6, Title = "a"
我想得到结果:
ID = 1, Title = "a"
ID = 2, Title = "b"
ID = 3, Title = "c"
ID = 4, Title = "ab"
ID = 5, Title = "a"
ID = 6, Title = "a"
我们看到,标题项目已使用list2中的项目替换。
可能最好的方式是使用LINQ。 有人知道这样做的热门方法吗?
由于您从第一个列表中省略了ID = 4, Title = "d"
,因此我假设您要从list1 + list2中获取所有项目,如果两个列表中都存在ID,则从第二个列表中获取一个项目。
然后,使用Except
+ Concat
这种方法有效:
var idOnlyList1 = List1.Select(x => x.Id).Except(List2.Select(x => x.Id));
var templates1 = from id in idOnlyList1 join lt1 in List1 on id equals lt1.Id select lt1;
List<ListTemplate> result = templates1.Concat(List2).ToList();
合并列表,对ID进行分组,然后选择分组中的最后一项(如果有多个匹配项,则为list2中的项)。
var q = list1.Concat(list2).GroupBy(x => x.Id).Select(x => x.Last());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.