【转载】C#中通过Distinct方法对List集合进行去重

在C#的List集合对象中,可以使用Distinct方法来对List集合元素进行去重,如果list集合内部元素为值类型,则Distinct方法根据值类型是否相等来判断去重,如果List集合内部元素为引用类型变量,则是判断相同引用的对象为相同进行List集合元素去重操作。

(1)值类型的List<int>集合对象intList,内部元素为1,1,2,2,3,4,5等这几个元素。对intList对象进行去重可使用下列语句:

  List<int> intList= new List<int>() { 1, 1,2,2,3,4,5};
 intList= intList.Distinct().ToList();

经过上述Distinct方法去重处理并重新赋值后,intList集合内部元素为:1,2,3,4,5。

(2)针对引用类型的Distinct方法去重,则是判断List集合中的对象引用地址是否一致,不一致的话为不同的两个对象,即使2个对象的每个属性值都一样的情况下。

   List<TestModel> testList = new List<ConsoleApplication1.TestModel>();
   testList.Add(new TestModel()
   {
       Index=1,
       Name="Index1"
   });
   testList.Add(new TestModel()
   {
       Index = 2,
       Name = "Index2"
   });
   testList.Add(new TestModel()
   {
       Index = 2,
       Name = "Index2"
   });
   testList = testList.Distinct().ToList();

上述程序语句中,虽然List集合testList中的第2个元素和第3个元素的属性值完全一样,但这2个元素依旧是不同的对象,因此在调用Distinct()方法去重后重新赋值,testList依旧不变。

 

posted @ 2019-06-15 09:48  江湖逍遥  阅读(8957)  评论(0编辑  收藏  举报