0

I want to select some fields from DataView and after selecting those fields want to apply .Distinct() on these set of fields.

Right now, I used this code :

DataView dvGroups = new DataView();
dvGroups = GetDataFromDatabase(); //-- Fill Dataview
var groups = dvGroups.Table.AsEnumerable()
                           .Where(x => x.Field<int>("GroupId") != 0)
                           .Select(p => p.Field<int>("GroupId"))
                           .Distinct()
                           .ToArray();

it's only selecting a single field (i.e "GroupId"). But, Now i want to select multiple fields (like "GroupId", "GroupName") and then get the distinct value.

How can i achieve this task?

xanatos
  • 109,618
  • 12
  • 197
  • 280
Ishan Jain
  • 8,063
  • 9
  • 48
  • 75

2 Answers2

1

You can create anonymous objects:

.Select(p => new {
    GroupId = p.Field<int>("GroupId"),
    Something = p.Field<string>("Something"),
})
.Distinct().ToArray();

for example, because anonymous types are "compatible" with Distinct() (see LINQ Select Distinct with Anonymous Types), because the compiler generates the Equals/GetHashCode methods.

Or you could use the Tuple:

.Select(p => Tuple.Create(p.Field<int>("GroupId"), p.Field<string>("Something")))

But they are normally less clear.

More complex is to create your class and implement the Equals and GetHashCode

Community
  • 1
  • 1
xanatos
  • 109,618
  • 12
  • 197
  • 280
1

You can use an anonymous type:

var groups = dvGroups.Table
          .AsEnumerable()
          .Where(x => x.Field<int>("GroupId") != 0)
           .Select(p => new 
                        { 
                            id = p.Field<int> ("GroupId"),
                            name = p.Field<string> ("Name"))
                        }).Distinct().ToArray();
Selman Genç
  • 100,147
  • 13
  • 119
  • 184