简体   繁体   English

如何使用LINQ从DataView中选择多个字段并应用.Distinct()

[英]How to select multiple fields from a DataView and apply .Distinct() using LINQ

I want to select some fields from DataView and after selecting those fields want to apply .Distinct() on these set of fields. 我想从DataView选择一些字段,选择这些字段后,要在这些字段集上应用.Distinct()。

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" ). 它只是选择一个字段(即"GroupId" )。 But, Now i want to select multiple fields (like "GroupId", "GroupName" ) and then get the distinct value. 但是,现在我想选择多个字段(例如"GroupId", "GroupName" ),然后获取不同的值。

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. 例如,由于匿名类型与Distinct() “兼容”(请参见LINQ选择与匿名类型不同 ),因为编译器会生成Equals / GetHashCode方法。

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 更复杂的是创建您的类并实现EqualsGetHashCode

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM