【C#】List求并集、交集、差集
- 值类型List
List<int> intList1 = new List<int>() { 1, 2, 3 };
List<int> intList2 = new List<int>() { 3, 4, 5 };
var result = intList1.Union(intList2);
Console.WriteLine($"并 {string.Join(',',result)}");
result = intList1.Intersect(intList2);
Console.WriteLine($"交 {string.Join(',', result)}");
result = intList1.Except(intList2);
Console.WriteLine($"差 {string.Join(',', result)}");
结果:
2. 对象类型List
List<Person> people = new List<Person>
{
new Person { Name = "Alice" },
new Person { Name = "Bob" },
new Person { Name = "Charlie" }
};
List<Person> people2 = new List<Person>
{
new Person { Name = "Alice" },
new Person { Name = "Joan" }
};
var abc = people.Union(people2).ToList();
Console.WriteLine($"并 { string.Join(',', abc.Select(s => s.Name))}");
abc = people.Where(s => people2.Any(x => x.Name == s.Name)).ToList();
Console.WriteLine($"Name交 {string.Join(',', abc.Select(s=>s.Name))}");
abc = people.Where(s =>! people2.Any(x => x.Name == s.Name)).ToList();
Console.WriteLine($"Name差 {string.Join(',', abc.Select(s => s.Name))}");
结果
3. 对象类型的还可以利用LINQ 左连接求交集、差集
var leftJoinQuery = from p in people
join pp in people2 on p.Name equals pp.Name into temp
from co in temp.DefaultIfEmpty()
where co is not null
select new { p.Name };
Console.WriteLine($"Name交 {string.Join(',', leftJoinQuery.Select(s => s.Name))}");
leftJoinQuery = from p in people
join pp in people2 on p.Name equals pp.Name into temp
from co in temp.DefaultIfEmpty()
where co is null
select new { p.Name };
Console.WriteLine($"Name差 {string.Join(',', leftJoinQuery.Select(s => s.Name))}");
结果: