在回答论坛有个某列不重复的值为条件获取数据的问题,而记录下来。
问题:源地址: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为数据源的解决方法:
List<Test> getlst = new List<Test>
{
new Test(){id=1,proname="abc",brandid=5,guigecategoryid=16},
new Test(){id=2,proname="bbb",brandid=5,guigecategoryid=16},
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为数据源的解决方法
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