【问题标题】:Linq, join, group, count > select more valuesLinq、加入、分组、计数 > 选择更多值
【发布时间】:2011-08-09 23:15:55
【问题描述】:

使用 LINQ,我正在执行以下操作来选择我的供应商及其产品数量:

from s in context.Suppliers 
join p in context.Products on s equals p.Supplier 
group s by s.CompanyName 
into result 
select new {   
    SupplierName = result.Key,   
    ProductCount = result.Count() 
}

这很好用,但我想从我的供应商表中选择更多属性,SupplierId 和 SupplierAddress,例如:

....    
select new {   
    SupplierName = result.Key,   
    ProductCount = result.Count(),   
    SupplierId = ..,   
    SupplierAddress = ..,  
    }

有人知道怎么做吗?

感谢您的帮助!

【问题讨论】:

  • 你在正确的轨道上,只需验证两件事......你的输出类是否有一个字段来存储 SupplierId 和 SupplierAddress?您只是粘贴部分代码,我们可以获取整行,包括 LINQ 吗?

标签: c# linq


【解决方案1】:

所以您确定所有具有相同CompanyNameSupplier 组都保证具有相同的IdAddress

from s in context.Suppliers 
join p in context.Products on s equals p.Supplier 
group s by s.CompanyName 
into result 
select new {   
    SupplierName = result.Key,   
    ProductCount = result.Count(),
    SupplierId = result.First().Id,
    SuppliedAddress = result.First().Address 
}

如果您改为按Id 或全部分组,看起来会更自然:

from s in context.Suppliers 
join p in context.Products on s equals p.Supplier 
group s by new { s.CompanyName, s.Id, s.Address } 
into result 
select new {   
    ProductCount = result.Count(),
    SupplierName = result.Key.CompanyName,   
    SupplierId = result.Key.Id,
    SuppliedAddress = result.Key.Address 
}

【讨论】:

  • 隐含在result.FirstOrDefault().Idresult.FirstOrDefault().Address 中是可能出现空异常。
  • 我同意辉煌。如果您要使用该值而不检查null,那么使用OrDefault 版本是没有意义的。
  • @svick:你说得对,出于某种原因,我认为 LINQ 中没有 First() 方法。这里已经很晚了,我想我需要睡觉了..
  • 是的,你完全正确,最好按 ID 分组,但我只是输入了这个作为一个简单的例子来说明我的问题。
  • 第二个例子非常适合!谢谢!
【解决方案2】:

编辑

嗯...除非我弄错了,否则这可以做得更干净:

context
    .Products
    .GroupBy(p=>p.Supplier)
    .Select(result=>new {
        SupplierName = result.Key,   
        ProductCount = result.Count(),
        SupplierId = result.Key.Id,   
        SupplierAddress = result.Key.Address,  
    }

连接来自数据库中的 FK 关系开箱即用,因此 Product 已经具有 Supplier。您似乎在自己的代码 (...equals p.Supplier) 中发现了此设置,然后未能理解其含义。为从理解语法更改为方法链而道歉。它们对我来说更自然。

补充@Dan 的评论(这对于 Linq2Objects 可能是正确的),在 Linq2Sql 中(我不能保证 L2E,但我想它大致相同),如果您按由 FK 关系生成的属性分组,生成的 SQL 将按键值分组,而不是整个实体。

【讨论】:

  • 请注意,您还需要 Supplier 来实现 IEquatable 才能使其工作。
  • @Dan,我扩展了我的答案以解决您的评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多