1. 程式人生 > >Linq實現DaTaTable或者List裡面資料值不重複

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