【问题标题】:Aggregate LINQ results聚合 LINQ 结果
【发布时间】:2010-11-20 14:45:13
【问题描述】:

如果我有一个 Publisher 表,其中包含许多书,并且每本书可以有多个作者,我如何获得一个出版商的不同作者列表?在 SQL 中,您只需连接所有表,选择作者,然后使用 SELECT DISTINCT。使用 LINQ 我最终得到一个 IEnumerable(Of EntitySet(of Author)):

Dim temp = From p in Publishers Select (From b in p.Books Select b.Author)

这仍然不能解决重复的作者。

有没有办法在单个查询中获取未分组的作者的平面列表?我知道我可以遍历这些集合并创建一个列表并在其上使用 Distinct。我很好奇它是否可以在一个语句中完成。

【问题讨论】:

    标签: asp.net linq linq-to-sql


    【解决方案1】:

    这是原始查询。

    var authorSets = Publishers
      .Where(...)
      .Select(p => p.Books.Select(b => b.Author));
    

    这是由 SelectMany 改进的同一个查询,用于扁平化层次结构。

    var authors = Publishers
      .Where(...)
      .SelectMany(p => p.Books.Select(b => b.Author))
      .Distinct();
    

    欲了解更多信息:MSDN

    【讨论】:

    • SelectMany 正是我想要的。谢谢。
    • 如果 GroupBy 是我的胶带,那么 SelectMany 就是我的电锯。
    【解决方案2】:

    如果您对 SQL 比对 lambda 表达式更熟悉,请尝试:

    from b in Books 
    join ba in BookAuthorIndexes on b.BookId equals ba.BookId 
    join a in Authors on ba.AuthorId equals a.AuthorId 
    where b.Publisher.Name = "foo" 
    select a distinct
    

    我在这里对您的架构做出了一些相当大的假设,但有些类似。

    【讨论】:

      【解决方案3】:

      这样的工作是否可行:

      在 C# 中:

      var publisherAuthors = Authors.Where(a => a.Books.Where(b => b.Publisher.Name.Equals("Some Publisher")));
      

      【讨论】:

      • 对我来说看起来不错,虽然有点挤在一条线上。建议将其拆分,或更改为查询语法以使其更具可读性 IMO
      • Books.Where() 返回一个 IQueryable。 Authors.Where() 需要一个布尔值 - 而不是 IQueryable。您的意思是使用 Books.Any() 吗?
      猜你喜欢
      • 2013-07-02
      • 2019-05-02
      • 2019-08-01
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多