C# 对List<T>取交集、差集以及并集

C# 对List取交集、差集以及并集

List fruits1 = new List { "apple", "banana", "orange", "pear" };
List fruits2 = new List { "grape", "banana", "watermelon", "pear" };

List filteredFruits = fruits1.Where(fruit => fruit.Contains("Layer")).ToList();//查找包含内容的同类集合
List intersectionFruits = fruits1.Intersect(fruits2).ToList(); //交集 表示两个List都存在的集合
foreach (string fruit in intersectionFruits)
{
    Console.WriteLine(fruit);
}

List differenceFruits = fruits1.Except(fruits2).Distinct().ToList(); //差集 表示fruits1存在fruits2不存在的集合
foreach (string fruit in differenceFruits)
{
    Console.WriteLine(fruit);
}

List unionFruits = fruits1.Union(fruits2).ToList(); //并集 并集的个数一般不会为0,除非list1和list2中的元素个数都为0
foreach (string fruit in unionFruits)
{
    Console.WriteLine(fruit);
}

 

 

你可能感兴趣的:(C#,c#)