How to Select Distinct Rows in a Datatable and Store into an Array

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


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

Distinct records in DataTable

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

Get Distinct String List From DataTable

Distinct returns IEnumerable<TSource> in your case it returns IEnumerable<String> and you are trying to get the List<String> in the output.

You need to change the code from

List<string> column1List = (returnDataTable.AsEnumerable().Select(x => x["Column1"].ToString()).ToList()).Distinct();


List<string> column1List = (returnDataTable.AsEnumerable().Select(x => x["Column1"].ToString()).Distinct().ToList();

Select distinct values from a large DataTable column

Method 1:

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

Method 2:
You will have to create a class matching your datatable column names and then you can use the following extension method to convert Datatable to List

    public static List<T> ToList<T>(this DataTable table) where T : new()
{
List<PropertyInfo> properties = typeof(T).GetProperties().ToList();
List<T> result = new List<T>();

foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties);
result.Add(item);
}

return result;
}

private static T CreateItemFromRow<T>(DataRow row, List<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var property in properties)
{
if (row.Table.Columns.Contains(property.Name))
{
if (row[property.Name] != DBNull.Value)
property.SetValue(item, row[property.Name], null);
}
}
return item;
}

and then you can get distinct from list using

      YourList.Select(x => x.Id).Distinct();

Please note that this will return you complete Records and not just ids.

Select distinct DataTable rows

The ToTable access a list of string params, the following should convert all your columns to array of string so you don't have to enter them manually

 System.Data.DataTable table = new System.Data.DataTable(); // already fulfilled table

DataView view = new DataView(table);
var tableDistinct = view.ToTable(true, table.Columns.Cast<DataColumn>().Select(z=>z.ColumnName).ToArray());

c# selecting distinct rows from datatable

You can try something like this...

DataTable results;
dt2.DefaultView.RowFilter = expression;
results = dt2.DefaultView.ToTable(true, "[name_of_column_0]");
foreach (DataRow row in results.rows)
{
...
}

View.ToTable function returns a datatable based on its own data. The first parameter determines if it will contain only different values and the second is a parameter array with the names of the columns you want to include in the datatable.

As stated in another answer, LINQ is also a good option if available.

How can I extract all Unique / Distinct Rows from a Datatable and save these rows in a new Datatable with same Columns?

A couple of options that allow to filter the DataRows of a DataTable, based on the value of a specific Column, to generate a new DataTable with the resulting DataRows.

Considering - since you mentioned it - that is not important which DataRow is selected, i.e., any duplicate DataRow would do:

(if the DataRow to select becomes important at some point, you could also OrderBy() the grouping using the value of another Column, then pick the first - or the last - DataRow from the ordered collection)

Group DataRows by the value of a Column:

  • Group the DataRows of the source DataTable using the value of a Column
  • Select the first DataRow of each grouping
  • Call the CopyToDataTable() method to generate a new DataTable

Resulting in:

Dim newDt = [DataTable].AsEnumerable().
GroupBy(Function(r) r("[Column Name]")).
Select(Function(g) g.First()).
CopyToDataTable()

Use a custom EqualityComparer:

  • Build a simple EqualityComparer class that compares the values of the same Column of two DataRows objects
  • Use the Distinct() method and pass the custom EqualityComparer, initialized with the name of the Column used as comparer
  • Call the CopyToDataTable() method

This method has the advantage that is reusable (i.e., you don't need to rebuild a query, just initialize the comparer with the name of the Column to compare)

Resulting in:

Dim newDt = [DataTable].AsEnumerable().
Distinct(New DataRowColumnComparer("[Column Name]")).
CopyToDataTable()

Custom EqualityComparer:

It's kind of a basic comparer. You can of course extend it to use different indexers (an integer representing the index of a Column, or a DataColumn reference).

Public Class DataRowColumnComparer
Implements IEqualityComparer(Of DataRow)

Private ReadOnly t As String = String.Empty

Public Sub New(key As String)
If String.IsNullOrEmpty(key) Then Throw New ArgumentException("Empty key")
t = key
End Sub

Public Overloads Function Equals(dr1 As DataRow, dr2 As DataRow) As Boolean Implements IEqualityComparer(Of DataRow).Equals
If dr1 Is Nothing AndAlso dr2 Is Nothing Then Return True
If dr1 Is Nothing OrElse dr2 Is Nothing Then Return False
Return dr1(t).Equals(dr2(t))
End Function

Public Overloads Function GetHashCode(dr As DataRow) As Integer Implements IEqualityComparer(Of DataRow).GetHashCode
If dr(t) Is Nothing OrElse dr(t) Is DBNull.Value Then Return 0
Return dr(t).GetHashCode()
End Function
End Class

How Select All Record From DataTable Distinct By Only One Column

See my comment under your question. If I understood you correctly, then I think this is what you want:

var inv_selected_date = temp.GroupBy(i => i.invoice_number).Select(iv => iv.First()).ToList();


Related Topics



Leave a reply



Submit