C# DataTable 中的不同记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15898688/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:20:53  来源:igfitidea点击:

Distinct records in DataTable

c#asp.netdatatabledataset

提问by Nomi Ali

I want to get distinct records based on some fields. I'm using the following method:

我想根据某些字段获得不同的记录。我正在使用以下方法:

string[] TobeDistinct = { "PKID" };
DataTable dtDistinct = GetDistinctRecords(ds.Tables[0], TobeDistinct);
DataSet ds2 = new System.Data.DataSet();
ds2.Tables.Add(dtDistinct);

public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
    DataTable dtUniqRecords = new DataTable();
    dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
    return dtUniqRecords;
}

This gives me the distinct records, but only two records come. Only two distinct PKID will come. For example, I have multiple records with PKID 10,12,14,16, but the result is 2 rows with PKID 10 and 12. More two rows are not there, but should be there. What do I need to do?

这给了我不同的记录,但只有两个记录来了。只有两个不同的 PKID 会来。例如,我有多个 PKID 为 10、12、14、16 的记录,但结果是 PKID 为 10 和 12 的 2 行。更多的两行不在那里,但应该在那里。我需要做什么?

I follow this article: http://www.codeproject.com/Tips/153008/Select-DISTINCT-records-based-on-specified-fields

我关注这篇文章:http: //www.codeproject.com/Tips/153008/Select-DISTINCT-records-based-on-specified-fields

enter image description here

在此处输入图片说明

采纳答案by ????

You can use like follows

您可以使用如下

DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "Column1", "Column2" ...);

More detail
How to select distinct rows in a datatable and store into an array

更多细节
如何在数据表中选择不同的行并存储到数组中

回答by Xelom

Can you try this?

你能试试这个吗?

var myResult = dt.AsEnumerable().Select(c => (DataRow)c["MyColumn"]).Distinct().ToList();