如何合并两个DbSet查询结果?已尝试同变量存储求方案
解决思路与代码示例
首先明确:你当前代码里的prod是List<ICollection<Product>>类型(嵌套的产品集合),copc是List<ICollection<ProductLine>>类型(嵌套的产品线集合),二者元素类型完全不同,自然无法直接合并。下面根据两种常见业务场景给出解决方案:
场景1:获取「指定利润中心下的指定产品线」的所有产品
直接通过关联查询一步到位,无需拆分两次查询:
public JsonResult GetProductByPDLN(int pdlnId, int copcCode) { _context.Configuration.ProxyCreationEnabled = false; // 直接筛选同时属于目标产品线、目标利润中心的产品 var products = _context.Products .Where(p => p.ProductLine.Id == pdlnId && p.ProductLine.ProfitCenter.Id == copcCode) .ToList(); return Json(products, JsonRequestBehavior.AllowGet); }
场景2:合并「指定产品线的产品」和「指定利润中心下所有产品线的产品」(去重)
先将两次查询的结果都扁平化为Product类型的集合,再合并去重:
public JsonResult GetProductByPDLN(int pdlnId, int copcCode) { _context.Configuration.ProxyCreationEnabled = false; // 扁平化指定产品线的产品集合 var pdlnProducts = _context.ProductLines .Where(pl => pl.Id == pdlnId) .SelectMany(pl => pl.Products) .ToList(); // 扁平化指定利润中心下所有产品线的产品集合 var copcProducts = _context.ProfitCenters .Where(pc => pc.Id == copcCode) .SelectMany(pc => pc.ProductLines) .SelectMany(pl => pl.Products) .ToList(); // 合并并去重(需根据Product的唯一标识判断) var mergedProducts = pdlnProducts.Union(copcProducts, new ProductEqualityComparer()).ToList(); return Json(mergedProducts, JsonRequestBehavior.AllowGet); } // 自定义产品比较器,用于Union去重 public class ProductEqualityComparer : IEqualityComparer<Product> { public bool Equals(Product x, Product y) { return x.Id == y.Id; } public int GetHashCode(Product obj) { return obj.Id.GetHashCode(); } }
失败原因说明
你之前的代码中,prod和copc是嵌套的不同类型集合,既不能用逻辑运算符&&拼接,也无法直接合并。核心是要通过SelectMany将嵌套集合「扁平化」为同类型的单层集合,再进行合并操作。
内容的提问来源于stack exchange,提问作者m.woods
相关产品推荐
相关产品推荐

