我有一个地址类。
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 的不同之处:省和市
即类似于
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();
但它不支持此查询。异常消息是:
Expression type 'NhDistinctExpression' is not supported by this SelectClauseVisitor.
我该怎么做?
最佳答案
您可以使用 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
方法,在 here 中使用另一个重载 Distinct