How to select distinct rows in a datatable and sto

2019-01-01 14:17发布

I have a dataset objds. objds contains a table named Table1. Table1 contains column named ProcessName. This ProcessName contains repeated names.So i want to select only distinct names.Is this possible.

  intUniqId[i] = (objds.Tables[0].Rows[i]["ProcessName"].ToString());

18条回答
伤终究还是伤i
2楼-- · 2019-01-01 14:56

it is easy

    DataView view = new DataView(dt);
DataTable dt2 = view.ToTable(true, "Column1", "Column2","Column3", ...,"ColumnNth");

and dt2 datatable contain column1,Column2..ColumnNth unique data.

查看更多
残风、尘缘若梦
3楼-- · 2019-01-01 14:57
君临天下
4楼-- · 2019-01-01 14:58
objds.Table1.Select(r => r.ProcessName).AsEnumerable().Distinct();
查看更多
栀子花@的思念
5楼-- · 2019-01-01 15:00

The most simple solution is use linq and then transform the result to a DataTable

    //data is a DataTable that you want to change
    DataTable result = data.AsEnumerable().Distinct().CopyToDataTable < DataRow > ();

This is valid for asp.net 4.0 ^ Framework if I remeber.

查看更多
后来的你喜欢了谁
6楼-- · 2019-01-01 15:01
string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);

//Following function will return Distinct records for Name, City and State column.
public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
    DataTable dtUniqRecords = new DataTable();
    dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
    return dtUniqRecords;
}
查看更多
千与千寻千般痛.
7楼-- · 2019-01-01 15:04

With LINQ (.NET 3.5, C# 3)

var distinctNames = ( from row in DataTable.AsEnumerable()
 select row.Field<string>("Name")).Distinct();

 foreach (var name in distinctNames ) { Console.WriteLine(name); }
查看更多
登录 后发表回答