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
- List<Test> getlst = new List<Test>
- {
- new Test(){id=1,proname="abc",brandid=5,guigecategoryid=16},
- new
- new Test(){id=3,proname="adc",brandid=7,guigecategoryid=3},
- new Test(){id=4,proname="aac",brandid=9,guigecategoryid=7},
- };
- var result = getlst.GroupBy(x => x.guigecategoryid).Select(x => x.First()).ToList();
- public class Test
- {
- public int id { get; set; }
- public string proname { get; set; }
- public int brandid { get; set; }
- public int guigecategoryid { get; set; }
- }
id proname brandid guigecategoryid
1 abc 5 16
3 adc 7 3
4 aac 9 7
DataTable為資料來源的解決方法
[csharp] view plain copy- DataTable dt = new DataTable();
- dt.Columns.AddRange(new DataColumn[]{
- new DataColumn("id", Type.GetType("System.Int32")),
- new DataColumn("proname", Type.GetType("System.String")),
- new DataColumn("brandid", Type.GetType("System.Int32")),
- new DataColumn("guigecategoryid",
- Type.GetType("System.Int32")),
- });
- dt.Rows.Add(1, "abc", 5, 16);
- dt.Rows.Add(2, "bbb", 5, 16);
- dt.Rows.Add(3, "adc", 7, 3);
- dt.Rows.Add(4, "aac", 9, 7);
- var result1 = dt.AsEnumerable().GroupBy(x =>
- x.Field<Int32>("guigecategoryid")).Select(x => x.First()).ToList();
- var result2 = from p in dt.AsEnumerable().GroupBy(x =>
- x.Field<Int32>("guigecategoryid")).Select(xx => xx.FirstOrDefault()).ToList()
- select p;
得到
id proname brandid guigecategoryid
1 abc 5 163 adc 7 3
4 aac 9 7