4

In SQL to get the DISTINCT values in a column I would do something like:

SELECT DISTINCT ColumnName FROM TableName;

I would like to do something like this but for a DataTable's DataColumn. I am aware of this way (follow this link) which does the usual intuitive way of using the fact that we can check if what we have Contains(whatWeWant) or not, and if it doesn't we can add it to some container of unique items. What I would like to know is if there is something like the following out there:

var uniqueObjects = dataTable.Columns[0].Distinct().ToList();

I am also aware from reading the Microsoft Docs that the DataColumn class does not have a method called Distinct but if there is something like this that you guys are aware of please let me know. If not I will resort to making a Distinct extension method with the intuitive way of using Contains.

G. LC
  • 794
  • 1
  • 8
  • 27

2 Answers2

6

If you add System.Data.DataSetExtensions to your project's references:

using System.Data;

var uniqueObjects = dataTable
     .AsEnumerable()
     .Select(row => row[0])
     .Distinct()
     .ToList();
  • 1
    Very clean answer I like it, Ill try it out – G. LC Aug 03 '18 at 19:27
  • By the way I would change the variable row to column since it goes through columns not rows – G. LC Aug 03 '18 at 19:38
  • It will, in fact, enumerate through an [System.Data.EnumerableRowCollection](https://msdn.microsoft.com/en-us/library/system.data.datatableextensions.asenumerable(v=vs.110).aspx). I would also recommend using the [Field](https://msdn.microsoft.com/en-us/library/bb360891(v=vs.110).aspx) extension as @m-kudi did below if you know the column's type ahead of time. – Kevin Bourassa-Houle Aug 03 '18 at 19:52
3

You can do like...

      var uniqueObjects =  dataTable.AsEnumerable().Select(x=>x.Field<ColumnType>("ColumnName")).Distinct().ToList();
mukesh kudi
  • 719
  • 6
  • 20