Search code examples
c#linqdatatablelinq-to-dataset

Select distinct from dataTable.AsEnumerable


I have a data table dtStudent with structure as follows

Id | Name | Class | RoomNum | Subject
---------------------------------------
1  | ABC  | 5     | 10      | Maths
1  | ABC  | 5     | 10      | Science
1  | ABC  | 5     | 10      | English

As You can see, it contains different data for subject column only.

Now, I want to get the value for class and RoomNum column. As the values are same for all rows, I am using following-

var stdDetails = from r in DtTable.AsEnumerable()
select new
    {
        Class = r.Field<string>("Class").ToString(),
        RoomNum = r.Field<string>("RoomNum").ToString()
    };

What to do next? I need the values 5 and 10. Any help?


Solution

  • Just add Distinct() call. Thus anonymous types have default Equals and GetHashCode implementations which use all their properties, you will get only distinct pairs of class and room number:

    var stdDetails = (from r in DtTable.AsEnumerable()
                      select new {
                          Class = r.Field<string>("Class"),
                          RoomNum = r.Field<string>("RoomNum")
                      }).Distinct();
    

    BTW you don't need to call ToString() on value return for field. It will be converted to type of generic parameter, i.e. to string in your case. Also it looks like you have integer values in these columns, so think about converting it to integer with r.Field<int>