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

一、获取集合内重复值

public void GetDuplicateValue()
{
    List<string> lisA = new List<string> { "A", "B", "C", "A" };
    //方式一 借助字典
    Dictionary<string, int> dic = new Dictionary<string, int>();
    lisA.ForEach(x =>
    {
        if (dic.ContainsKey(x))
            dic[x] += 1;
        else
            dic[x] = 0;
    });
    List<string> lisDupValues = dic.Where(x => x.Value > 0).Select(x => x.Key).ToList();  //结果{"A"}
 
    //方式二
    List<string> lisDupValues2 = lisA.GroupBy(x => x).Where(x => x.Count() > 1).Select(x => x.Key).ToList(); //结果{"A"}
 
    //方式三 等同于方式二
    List<string> lisDupValues3 = (from r in lisA group r by r into g where g.Count() > 1 select g.Key).ToList(); //结果{"A"}
}

 二、单个集合操作

1、All、Any

    public void All_Any()
    {
        List<string> lisA = new List<string> { "A", "B", "C", "A" };
        //All:确定序列中的所有元素是否都满足条件
        bool all = lisA.All(x => x.Equals("B")); //结果 false
     
        //Any:确定序列中的任何元素是否存在或满足条件。
        bool any = lisA.Any(x => x.Equals("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 = lisA.Sum();  //结果 8
 
    //Average:计算数值序列的平均值。
    double average = lisA.Average();  //结果 2
 
    //Distinct:返回序列中的非重复元素
    List<int> distinctLisA = lisA.Distinct().ToList();  //结果 {1,2,3}
 
    //Max:返回值序列中的最大值。
    double max = lisA.Max();  //结果 3
 
    //Min:返回值序列中的最小值。
    double min = lisA.Min(); //结果 1
 
    //Select:将序列中的每个元素投影到新表单。
    var query = lisA.Select((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 = lisA.Skip(3).ToList();  //结果 {3}
 
    //Take:从序列的开头返回指定数量的相邻元素。
    List<int> task = lisA.Take(2).ToList();  //结果 {1,2}
 
    //ToDictionary:根据指定的键选择器函数、比较器和元素选择器函数,从 IEnumerable<T> 创建一个 Dictionary<TKey,TValue>。
    var dic = lisA.Distinct().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 = lisA.Concat(lisB).ToList();  //结果 { "A", "B", "C", "A" ,"A", "B", "H", "K"}
 
    //Except:生成两个序列的差集。
    List<string> onlyInLisASet = lisA.Except(lisB).ToList();   //结果 {"C"}
 
    //Intersect:生成两个序列的交集。
    List<string> duplicates = lisA.Intersect(lisB).ToList();  //结果 {"A","B"}
 
    //Union:生成两个序列的并集。
 
    List<string> union = lisA.Union(lisB).ToList();  //结果 { "A", "B", "C", "H", "K"}
 
    //Zip:将指定函数应用于两个序列的对应元素,以生成结果序列。
        List<string> zip=lisA.Zip(lisB, (first, second) => first + " " + second).ToList(); //结果 { "A A", "B B", "C H", "A K" }
}
原文地址:https://www.cnblogs.com/netcs/p/14722112.html