Linq实现DaTaTable或者List里面数据值不重复

在回答论坛有个某列不重复的值为条件获取数据的问题,而记录下来。

问题:源地址:http://bbs.csdn.net/topics/390887849?page=1#post-398200802

id  proname  brandid  guigecategoryid
1      abc            5              16
2      bbb            5              16
3      adc            7               3
4      aac            9               7

字段 (guigecategoryid)中 值去掉重复值,想得到结果如下
id  proname  brandid  guigecategoryid
1      abc            5              16
3      adc            7               3
4      aac            9               7

注意:得到的是一个结果集,有多列存在,不是仅仅对一列筛选
可以用dataview.totable()
可以用linq to sql
可以用distinct

List为数据源的解决方法

[csharp]  view plain  copy
  1.   List<Test> getlst = new List<Test>  
  2.                {  
  3.                     new Test(){id=1,proname="abc",brandid=5,guigecategoryid=16},  
  4.                     new Test(){id=2,proname="bbb",brandid=5,guigecategoryid=16},  
  5.                     new Test(){id=3,proname="adc",brandid=7,guigecategoryid=3},  
  6.                     new Test(){id=4,proname="aac",brandid=9,guigecategoryid=7},  
  7.                };  
  8.                var result = getlst.GroupBy(x => x.guigecategoryid).Select(x => x.First()).ToList();  
  9.  public class Test  
  10.      {  
  11.           public int id { getset; }  
  12.           public string proname { getset; }  
  13.           public int brandid { getset; }  
  14.           public int guigecategoryid { getset; }    
  15.      }   
得到

id  proname  brandid  guigecategoryid
1      abc            5              16
3      adc            7               3
4      aac            9                7

DataTable为数据源的解决方法

[csharp]  view plain  copy
  1.  DataTable dt = new DataTable();  
  2.                dt.Columns.AddRange(new DataColumn[]{    
  3.                    new DataColumn("id", Type.GetType("System.Int32")),    
  4.                    new DataColumn("proname", Type.GetType("System.String")),    
  5.                new DataColumn("brandid", Type.GetType("System.Int32")),    
  6.                new DataColumn("guigecategoryid",   
  7.                            Type.GetType("System.Int32")),    
  8.                   });  
  9.                dt.Rows.Add(1, "abc", 5, 16);  
  10.                dt.Rows.Add(2, "bbb", 5, 16);  
  11.                dt.Rows.Add(3, "adc", 7, 3);  
  12.                dt.Rows.Add(4, "aac", 9, 7);  
  13.                var result1 = dt.AsEnumerable().GroupBy(x =>   
  14. x.Field<Int32>("guigecategoryid")).Select(x => x.First()).ToList();  
  15.   
  16.                var result2 = from p in dt.AsEnumerable().GroupBy(x =>  
  17. x.Field<Int32>("guigecategoryid")).Select(xx => xx.FirstOrDefault()).ToList()   
  18. select p;  

得到

id  proname  brandid  guigecategoryid

1      abc            5              16
3      adc            7               3
4      aac            9               
7

猜你喜欢

转载自blog.csdn.net/shan1774965666/article/details/78082275