C# DataTable Linq 选择列等于“x”的不同值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16899160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# DataTable Linq select distinct values where column equals 'x'
提问by
I have a Datatable (Groups) designed like so
我有一个像这样设计的数据表(组)
I basically want to select from columna where it's X and get the disinct from ColumnB
This is what I have
var names = (from DataRow dr in Groups.Rows
orderby (string)dr["ColumnB"]
select (string)dr["ColumnB"]).Distinct();
This will give me distinct but it gives me Purple, and i dont want purple.
Thanks!
我基本上想从 columna 中选择它是 X 并从 ColumnB 中获取 disinct
这就是我所拥有的
var names = (from DataRow dr in Groups.Rows
orderby (string)dr["ColumnB"]
select (string)dr["ColumnB"]).Distinct();
这会给我不同的但它给我紫色,我不想要紫色。
谢谢!
回答by tucaz
If your return has more than one value and you want to Distinct the whole set by just one of the values you should use a custom IEqualityComparer.
如果您的回报有多个值,并且您想通过其中一个值区分整个集合,则应使用自定义IEqualityComparer。
var names = (from DataRow dr in Groups.Rows
where (string)dr["ColumnA"] == "X"
orderby (string)dr["ColumnB"]
select new {
ColumnA = (string)dr["ColumnA"],
ColumnB = (string)dr["ColumnB"]
}).Distinct(new MyCustomEqualityComparer());
edit:to include where clause
编辑:包括 where 子句
edit2:changed to custom IEqualityComparer
edit2:改为自定义 IEqualityComparer
回答by sarwar026
var names = (from DataRow dr in Groups.Rows
where dr["ColumnA"] == "X"
orderby (string)dr["ColumnB"]
select (string)dr["ColumnB"]).Distinct();
回答by Jason Politis
DataTable dt2 = dt1.Select("ColumnA = 'X'").CopyToDataTable().DefaultView.ToTable(true, "ColumnB");
So here we are selecting only the rows of data that you want, only rows where columnA is X. Then we choose only to see columnB, but with unique values only. Doing it in this order, you'll receive another datatable to play with. It'll only contain 1 column, columnB, and it'll only have unique/distinct values.
所以这里我们只选择你想要的数据行,只选择 columnA 为 X 的行。然后我们选择只查看 columnB,但只有唯一值。按照这个顺序做,你会收到另一个数据表来玩。它只包含 1 列 columnB,并且它只有唯一/不同的值。
Enjoy.
享受。

