using System; using System.Linq; namespace LinqDemo { /// <summary> /// https://www.cnblogs.com/LifeDecidesHappiness/p/8079214.html /// Linq 合集 交集 补集 去重 /// LDH @ 2021-9-15 /// </summary> internal class Program { private static void Main() { Console.Title = "Linq 合集 交集 补集 去重"; UseLinq(); Console.ReadKey(); } /// <summary> /// Linq 合集 交集 补集 去重 /// </summary> private static void UseLinq() { int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; // 合集 var unionResults = numbersA.Union(numbersB); Console.WriteLine("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Union ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"); foreach (var unionResult in unionResults) Console.WriteLine(unionResult); // 交集 var intersectResults = numbersA.Intersect(numbersB); Console.WriteLine( "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Intersect ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"); foreach (var intersectResult in intersectResults) Console.WriteLine(intersectResult); // 补集 var exceptResults = numbersA.Except(numbersB); Console.WriteLine("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Except ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"); foreach (var exceptResult in exceptResults) Console.WriteLine(exceptResult); // 去重 int[] numbers = { 0, 2, 2, 3, 3, 5, 5, 6, 8, 8, 8 }; var removeSameResults = numbers.Distinct(); Console.WriteLine( "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Distinct ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"); foreach (var removeSameResult in removeSameResults) Console.WriteLine(removeSameResult); } } }