1

I'm trying to return a set of distinct values from a DataTable using LINQ.

This is my code without the 'Distinct' part as I'm struggling to formulate the proper linq statement:

 DataTable gridData = RgClientData.DataSource as DataTable;
   var results = from myRow in gridData .AsEnumerable()
             select (myRow.Field<string>("AssignedUser"));

Just adding "Distinct()" to the end of the select does not work. I'm wrestling with the syntax because I don't fully understand how the 'Distinct' part relates to the Linq query.

Could someone point me in the right direction...thanks

Chris B
  • 5,311
  • 11
  • 45
  • 57

3 Answers3

6

Your query needs to be enclosed within parentheses in order to add Distinct to the end of it:

var results = (from myRow in gridData .AsEnumerable()
              select myRow.Field<string>("AssignedUser")).Distinct();

Or you could switch to the fluent syntax:

var results = gridData.AsEnumerable()
                      .Select(myRow => myRow.Field<string>("AssignedUser"))
                      .Distinct();
Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
  • Thank you, this works great and has also made me realise why I was getting so confused - I didn't appreciate there are two ways of writing LINQ expressions. This has lead me to [this other question](http://stackoverflow.com/questions/214500/which-linq-syntax-do-you-prefer-fluent-or-query-expression) for further reading... – Chris B Jun 08 '12 at 15:25
0

Try this:

 var results = (from myRow in gridData .AsEnumerable()
             select (myRow.Field<string>("AssignedUser")).Distinct();
Kapil Khandelwal
  • 15,958
  • 2
  • 45
  • 52
0
string[] distinctcolumn = (from b in datatable1.AsEnumerable()
                           select b.Field<string>"colimnname")).Distinct().ToArray();

columnname is the name of column whose distinct values you want

you get string array distinctcolumn you can use it as you need to.

codemirror
  • 3,164
  • 29
  • 42
  • This is exactly the same as the accepted answer from 4 months ago. At the risk of stating the obvious, you should check that no-one has already posted your answer before writing a post - at least check the accepted answer... – Chris B Oct 21 '13 at 09:03