我有一个地址类。
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();
但它不支持此查询。异常消息是:Expression type 'NhDistinctExpression' is not supported by this SelectClauseVisitor.
我该怎么做?