- 求交并差集主要利用了查询表达式LINQ的扩展方法。
using System;
using System.Collections.Generic;
using System.Linq;
namespace _01
{
class Program
{
static void Main(string[] args)
{
List<object> list1 = new List<object>() {
1, 'a', "b" };
List<object> list2 = new List<object>() {
2, 'a', "b" };
List<object> list3 = null;
Console.WriteLine("list1和list2共有的元素:");
list3 = Test.GetIntersect(list1, list2);
foreach (var item in list3)
{
Console.Write($"{
item}\t");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("list1和list2所有的元素:");
list3 = Test.GetUnion(list1, list2);
foreach (var item in list3)
{
Console.Write($"{
item}\t");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("list1比list2多的元素:");
list3 = Test.GetExcept(list1, list2);
foreach (var item in list3)
{
Console.Write($"{
item}\t");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("list2比list1多的元素:");
list3 = Test.GetExcept(list2, list1);
foreach (var item in list3)
{
Console.Write($"{
item}\t");
}
Console.WriteLine();
Console.WriteLine();
}
}
class Test
{
/// <summary>
/// 获取交集
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list1"></param>
/// <param name="list2"></param>
/// <returns></returns>
public static List<T> GetIntersect<T>(List<T> list1, List<T> list2)
{
return list1.Intersect<T>(list2).ToList();
}
/// <summary>
/// 获取并集
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list1"></param>
/// <param name="list2"></param>
/// <returns></returns>
public static List<T> GetUnion<T>(List<T> list1, List<T> list2)
{
return list1.Union<T>(list2).ToList();
}
/// <summary>
/// 获取差集
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list1"></param>
/// <param name="list2"></param>
/// <returns></returns>
public static List<T> GetExcept<T>(List<T> list1, List<T> list2)
{
return list1.Except<T>(list2).ToList();
}
}
}