C#两个list集合实体去重复
时间: 2023-07-20 11:44:36 浏览: 59
如果你想要对两个List集合中的实体对象进行去重,可以使用`DistinctBy`函数。这个函数需要使用第三方库`MoreLINQ`,示例代码如下:
```
using System;
using System.Collections.Generic;
using System.Linq;
using MoreLinq;
class Program
{
static void Main(string[] args)
{
List<Person> list1 = new List<Person>
{
new Person { Id = 1, Name = "Alice" },
new Person { Id = 2, Name = "Bob" },
new Person { Id = 3, Name = "Charlie" }
};
List<Person> list2 = new List<Person>
{
new Person { Id = 2, Name = "Bob" },
new Person { Id = 3, Name = "Charlie" },
new Person { Id = 4, Name = "David" }
};
List<List<Person>> listCollection = new List<List<Person>> { list1, list2 };
var mergedList = listCollection.SelectMany(l => l).DistinctBy(p => p.Id).ToList();
Console.WriteLine(string.Join(",", mergedList.Select(p => p.Name)));
}
}
class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
```
输出结果为:`Alice,Bob,Charlie,David`。
这里使用`DistinctBy`函数对两个List集合中的Person对象进行去重,按照Id属性进行去重。注意需要先引入`System.Linq`和`MoreLinq`命名空间,才能使用相关的函数。