c# - 某些专栏如何在linq & linq to NHibernate中使用Distinct

标签 c# linq distinct linq-to-nhibernate

我有一个地址类。

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,它使用 ProvinceCity 作为 EqualGetHashCode 方法与另一个重载 Distinct in here

关于c# - 某些专栏如何在linq & linq to NHibernate中使用Distinct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12726166/

相关文章:

linq - Linq 查询结果的返回数据类型

python - Django:在外键上不同,然后排序

Mysql 计数不同的结果

c# - 是否可以创建一个通用的 Session.QueryOver<T>?

c# - 将小数从 LINQ 查询转换为货币

c# - NHibernate - 如何审计实体的所有领域?

c# - 如何在 C# 中使用 Linq 将函数应用于列表中的每个元素,就像 python 中的方法 reduce() 一样?

php - MySQL GROUP By 和 ORDER BY 冲突

c# - 使用 EF 在 db 中建模树状结构

c# - XmlSerializer 未序列化为有效的 xml