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 (ie "GroupId"
). But, Now i want to select multiple fields (like "GroupId", "GroupName"
) and then get the distinct value.
How can i achieve this task?
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
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.