我有一个地址类。
public class Address : RootEntityBase
{
virtual public string Province { set; get; }
virtual public string City { set; get; }
virtual public string PostalCode { set; get; }
}
通过这个默认值:
var myList = new List<Address>
{
new Address {Province = "P1", City = "C1", PostalCode = "A"},
new Address {Province = "P1", City = "C1", PostalCode = "B"},
new Address {Province = "P1", City = "C1", PostalCode = "C"},
new Address {Province = "P1", City = "C2", PostalCode = "D"},
new Address {Province = "P1", City = "C2", PostalCode = "E"},
new Address {Province = "P2", City = "C3", PostalCode = "F"},
new Address {Province = "P2", City = "C3", PostalCode = "G"},
new Address {Province = "P2", City = "C3", PostalCode = "H"},
new Address {Province = "P2", City = "C4", PostalCode = "I"}
};
我需要通过两列提取这个 myList 的区别:Province & City
即类似于myExpertResult
:
var myExpertResult = new List<Address>
{
new Address {Province = "P1", City = "C1"},
new Address {Province = "P1", City = "C2"},
new Address {Province = "P2", City = "C3"},
new Address {Province = "P2", City = "C4"}
};
所以我使用这段代码:
var list = myList.Select(x => new Address {City = x.City, Province = x.Province}).Distinct().ToList();
但我的结果无效,因为结果的计数是 9,即所有地址。
SQL 中的等效查询是:select distinct Province , City from tblAddress
我还通过 linq to NHibernate 测试了这个查询。
var q = SessionInstance.Query<Address>();
.Select(x => new Address { Province = x.Province, City = x.City }).Distinct().ToList();
但不支持此查询。异常消息是:此 SelectClauseVisitor 不支持表达式类型“NhDistinctExpression”。
我该怎么做?
最佳答案
您可以使用GroupBy
:
var result = myList.GroupBy(a => new { a.Province, a.City })
.Select(g => new Address {
Province = g.Key.Province,
City = g.Key.City
});
或者使用匿名类型:
myList.Select(a => new {
Province = a.Province,
City = a.City
})
.Distinct();
默认情况下,匿名类型使用值质量进行比较,所有属性都等价则等价。
另一种方法是客户 EqualityComparer
,它使用 Province
和 City
作为 Equal
和 GetHashCode
方法与另一个重载 Distinct
in here
关于c# - 某些专栏如何在linq & linq to NHibernate中使用Distinct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12726166/