有些列如何在linq和linq中使用区分NHibernate

Ehs*_*san 4 c# linq distinct linq-to-nhibernate

我有一个Address类.

public class Address : RootEntityBase
{
    virtual public string Province { set; get; }
    virtual public string City { set; get; }        
    virtual public string PostalCode { set; get; }
}
Run Code Online (Sandbox Code Playgroud)

通过此默认值:

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"}
             };
Run Code Online (Sandbox Code Playgroud)

我需要通过两列来提取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"}
                        }; 
Run Code Online (Sandbox Code Playgroud)

所以我使用这段代码:

var list = myList.Select(x => new Address {City = x.City, Province = x.Province}).Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)

但是我的结果无效,因为结果的计数是9,即所有地址.

SQL中的等价查询是: select distinct Province , City from tblAddress

我也通过linq对NHibernate测试了这个查询.

var q = SessionInstance.Query<Address>();
        .Select(x => new Address { Province = x.Province, City = x.City }).Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)

但它不支持此查询.异常消息是:Expression type 'NhDistinctExpression' is not supported by this SelectClauseVisitor.

我该怎么做?

cuo*_*gle 11

你可以使用GroupBy:

var result = myList.GroupBy(a => new { a.Province, a.City })
      .Select(g => new Address { 
                  Province = g.Key.Province, 
                  City = g.Key.City 
              });
Run Code Online (Sandbox Code Playgroud)

或使用匿名类型:

 myList.Select(a => new { 
            Province = a.Province,
            City = a.City
        })
      .Distinct();
Run Code Online (Sandbox Code Playgroud)

默认情况下,匿名类型使用值质量进行比较,当所有属性都相同时,它是等效的.

另一种方式是客户EqualityComparer,它使用ProvinceCity用于EqualGetHashCode方法与其他重载Distinct这里

  • 我认为你可以在第一个查询中使用Key而不是First. (2认同)