c# - 分组而不复制供应商行

标签 c# .net linq linq-to-sql

使用 Linq-to-SQL 从 3 个表从 NorthWind 获取数据时遇到问题:

  1. 供应商
  2. 产品
  3. 类别

我想获取属于 categoryId > 3 类别的所有产品的供应商。结果集每个供应商需要 1 行,然后是一些包含每个产品一行(包括类别信息)的子集。这个想法是这个结果集将作为 ajax 调用的 json 值返回。

以下是我迄今为止所做工作的最简单版本:

from sups in Suppliers
join prods in Products on sups.SupplierID equals prods.SupplierID
join cats in Categories on prods.CategoryID equals cats.CategoryID
where ( cats.CategoryID > 3)

group sups by sups.SupplierID into g
select g

在 LinqPad 中,结果集看起来包含许多重复的供应商。 有什么想法吗?

编辑: 感谢 Adduci 的回答,我得到了以下有效的 LINQ 语句:

from sups in Suppliers
join prods in Products on sups.SupplierID equals prods.SupplierID
join cats in Categories on prods.CategoryID equals cats.CategoryID
where cats.CategoryID > 3
group new { sups, prods, cats } by new { sups.SupplierID, sups.CompanyName } into g
select new 
{
  g.Key,
  ProductInfo = from x in g
                 select new
                 {
                    ProductProperty = x.prods.ProductName,
                    CategoryProperty = x.cats.CategoryName
                 }  
}

额外的 by new { sups.SupplierID, sups.CompanyName } 完成了包含供应商字段的结果集。不错!

最佳答案

第一步是使用匿名类将您的 3 个表组合在一起

group new { sups, prods, cats } 

而不是 select g这是一个 ( IGrouping<...> ) 你应该像这样明确定义你想要的属性:

from sups in Suppliers
join prods in Products on sups.SupplierID equals prods.SupplierID
join cats in Categories on prods.CategoryID equals cats.CategoryID
where cats.CategoryID > 3
group new { sups, prods, cats } by sups.SupplierID into g
select new 
{
  Supplier = g.Key,
  ProductInfo = from x in g
                 select new
                 {
                    ProductProperty = x.prods.Prop1,
                    CategoryProperty = x.cats.Prop1
                 }  
}

这样你就可以避免从数据库中返回未使用的信息

关于c# - 分组而不复制供应商行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30991568/

相关文章:

c# - 什么是 "throw"

c# - 从服务在事件用户 session 中启动程序?

c# - 如何在 C# .NET 中实现 OAuth2 提供者和消费者

c# - MEF 如何设法实例化作为外部程序集的内部类的导出部件?

c# - 在 LINQ 表达式中将 Int 转换为 String

c# - 如何为 TCP/IP 事务计时

c# - 在不同时间需要返回值时将任务链接在一起的正确方法 #2

c# - Bot Framework V4 IActivityLogger

c# - 使用第一对作为种子聚合

C# Linq to XML 检查元素是否存在