C# List集合中获取重复值及集合运算

时间:2025-03-10 13:45:59

话不多说,直接上实例:

一、获取集合内重复值

public void GetDuplicateValue()
{
    List<string> lisA = new List<string> { "A", "B", "C", "A" };
    //方式一 借助字典
    Dictionary<string, int> dic = new Dictionary<string, int>();
    (x =>
    {
        if ((x))
            dic[x] += 1;
        else
            dic[x] = 0;
    });
    List<string> lisDupValues = (x =>  > 0).Select(x => ).ToList();  //结果{"A"}

    //方式二
    List<string> lisDupValues2 = (x => x).Where(x => () > 1).Select(x => ).ToList(); //结果{"A"}

    //方式三 等同于方式二
    List<string> lisDupValues3 = (from r in lisA group r by r into g where () > 1 select ).ToList(); //结果{"A"}
}

  由上述可看出方式二、三的写法非常简洁。便去Microsoft官网了解下了,又发现了许多新的东西,Linq还真是挺好用的

二、单个集合操作

1、All、Any

public void All_Any()
{
    List<string> lisA = new List<string> { "A", "B", "C", "A" };
    //All:确定序列中的所有元素是否都满足条件
    bool all = (x => ("B")); //结果 false

    //Any:确定序列中的任何元素是否存在或满足条件。
    bool any = (x => ("B"));  //结果 true
}

2、Sum、Average、Distinct、Max、Min、Select、Skip、Take、ToDictionary

public void Sum_Average_Distinct_Max_Min_Skip_Take_ToDictionary()
{
    List<int> lisA = new List<int> { 1, 2, 2, 3 };

    //Sum:计算数值序列的和。
    double sum = ();  //结果 8

    //Average:计算数值序列的平均值。
    double average = ();  //结果 2

    //Distinct:返回序列中的非重复元素
    List<int> distinctLisA = ().ToList();  //结果 {1,2,3}

    //Max:返回值序列中的最大值。
    double max = ();  //结果 3

    //Min:返回值序列中的最小值。
    double min = (); //结果 1

    //Select:将序列中的每个元素投影到新表单。
    var query = ((age, index) => new { index, jn = age + 1 }); //结果:{index=0,jn=2},{index=1,jn=3},{index=2,jn=3},{index=3,jn=4}

    //Skip:跳过序列中指定数量的元素,然后返回剩余的元素。
    List<int> lowerGrades = (3).ToList();  //结果 {3}

    //Take:从序列的开头返回指定数量的相邻元素。
    List<int> task = (2).ToList();  //结果 {1,2}

    //ToDictionary:根据指定的键选择器函数、比较器和元素选择器函数,从 IEnumerable<T> 创建一个 Dictionary<TKey,TValue>。
    var dic = ().ToDictionary(x => x); //结果 {{1,1},{2,2},{3,3}}
}

三、集合间运算

1、Concat、Except、Intersect、Union、Zip

public void Concat_Except_Intersect_Union_Zip()
{
    List<string> lisA = new List<string> { "A", "B", "C", "A" };
    List<string> lisB = new List<string> { "A", "B", "H", "K" };

    //Concat:连接两个序列。
    List<string> query = (lisB).ToList();  //结果 { "A", "B", "C", "A" ,"A", "B", "H", "K"}

    //Except:生成两个序列的差集。
    List<string> onlyInLisASet = (lisB).ToList();   //结果 {"C"}

    //Intersect:生成两个序列的交集。
    List<string> duplicates = (lisB).ToList();  //结果 {"A","B"}

    //Union:生成两个序列的并集。

    List<string> union = (lisB).ToList();  //结果 { "A", "B", "C", "H", "K"}

    //Zip:将指定函数应用于两个序列的对应元素,以生成结果序列。
        List<string> zip=(lisB, (first, second) => first + " " + second).ToList(); //结果 { "A A", "B B", "C H", "A K" }
}