• 利用C#怎么获取 List集合中的重复值Linq操作


    跟大家聊聊有关利用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"}
    }

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

    二、单个集合操作

    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、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" }
    }

    补充知识:c#中List的元素遍历(foreach)和去重复(distinct)

    一、准备工作

    定义实体类people

    public List<People> PeopleList { get; set; }
    
      public class People
      {
        public string Name { get; set; }
        public int Age { get; set; }
      }

    实体比较help类

    public delegate bool CompareDelegate<T>(T x, T y);
      public class ListCompare<T> : IEqualityComparer<T>
      {
        private CompareDelegate<T> _compare;
        public ListCompare(CompareDelegate<T> d)
        {
          this._compare = d;
        }
    
        public bool Equals(T x, T y)
        {
          if (_compare != null)
          {
            return this._compare(x, y);
          }
          else
          {
            return false;
          }
        }
    
        public int GetHashCode(T obj)
        {
          return obj.ToString().GetHashCode();
        }
      }

    二、List.ForEach()

    假设需要对集合中的每个元素进行运算(将每个人的年龄增加10岁)

      PeopleList.ForEach(p=>{
        p.Age = p.Age + 10;
      });

    三、List.Distinct()

    假设需要将姓名和年龄相同的元素过滤掉

    PeopleList.Distinct(new Common.List.ListCompare<People>(
        (x,y)=> x.Name==y.Name&&x.Age==y.Age)
    );

    解析:

    ListCompare类用来比较List中的两个元素。它的构造函数中需要传入一个CompareDelegate。

    可以看出,两个元素的比较,重点在CompareDelegate中。

    定义: public delegate bool CompareDelegate(T x, T y);

    其实,ListCompare实现了IEqualityComparer接口。

    看完上述内容,你们对利用C#怎么获取 List集合中的重复值有进一步的了解吗?

     

    转 :https://www.yisu.com/zixun/323197.html

    涉及lambda讲解中间有Linq:  https://www.bilibili.com/video/BV1B5411w7kZ?spm_id_from=333.999.0.0

  • 相关阅读:
    C#事件解析
    VB 正则表达式应用
    vb.net 2进制、8进制、10进制、16进制...各种进制间的轻松转换
    .net 中的委托(delegate)的使用和原理
    什么是Color LUT/Color Map
    Java怀旧:About left/right shift, negative value representation and signextended(while shifting)
    Eclipse Tips
    Setup KGDB
    Java怀旧:foreach version loop, Changes to iteration variable doesn't take effect
    Java怀旧:break <label> & continue <label>,break <label>相当于简易的goto了,凑活用了
  • 原文地址:https://www.cnblogs.com/fps2tao/p/16355863.html
Copyright © 2020-2023  润新知