You can use ToTable(distinct As Boolean, ParamArray columnNames As String()) method for this. This will return distinct Users for you. You can add multiple column names if you want.
A DataView enables you to create different views of the data stored in a DataTable, a capability that is often used in data-binding applications. Using a DataView, you can expose the data in a table with different sort orders, and you can filter the data by row state or based on a filter expression.
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "Column1", "Column2" ...);
Following single line of code will avoid the duplicate rows of a DataTable
:
dataTable.DefaultView.ToTable(true, "employeeid");
Where:
first parameter in ToTable()
is a boolean which indicates whether you want distinct rows or not.
second parameter in the ToTable()
is the column name based on which we have to select distinct rows. Only these columns will be in the returned datatable.
The same can be done from a DataSet
, by accessing a specific DataTable
:
dataSet.Tables["Employee"].DefaultView.ToTable(true, "employeeid");
DataTable dt = new DataTable();
dt.Columns.Add("IntValue", typeof(int));
dt.Columns.Add("StringValue", typeof(string));
dt.Rows.Add(1, "1");
dt.Rows.Add(1, "1");
dt.Rows.Add(1, "1");
dt.Rows.Add(2, "2");
dt.Rows.Add(2, "2");
var x = (from r in dt.AsEnumerable()
select r["IntValue"]).Distinct().ToList();
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); }
You can use like that:
data
is DataTable
data.DefaultView.ToTable(true, "Id", "Name", "Role", "DC1", "DC2", "DC3", "DC4", "DC5", "DC6", "DC7");
but performance will be down. try to use below code:
data.AsEnumerable().Distinct(System.Data.DataRowComparer.Default).ToList();
For Performance ; http://onerkaya.blogspot.com/2013/01/distinct-dataviewtotable-vs-linq.html
var distinctRows = (from DataRow dRow in dtInventory.Rows
select dRow["column_name"] ).Distinct();
var distinctRows = (from DataRow dRow in dtInventory.Rows
select dRow["col1"], dRow["col2"].. ).Distinct();
To improve the above answer: The ToTable function on dataview has a "distinct" flag.
//This will filter all records to be distinct
dt = dt.DefaultView.ToTable(true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With