c# - 从单个(平面)数据库查询创建复合对象的方法

标签 c# linq

我通过 SQL 查询从我们的 ERP 获取产品数据,由此返回的数据在大小级别非常平坦。一个产品有 3 个级别:

  • 风格
  • 颜色
  • 尺寸

一种款式有多种颜色,一种颜色有多种尺码。

我创建了以下模型:

public class Ap21Style
{
    public int StyleIdx;
    public string StyleCode;
    public IList<Ap21Clr> Clrs { get; set; } = new List<Ap21Clr>();
}

public class Ap21Clr
{
    public int ClrIdx { get; set; }
    public string ColourCode { get; set; }
    public string ColourName { get; set; }
    public string ColourTypeCode { get; set; }
    public string ColourTypeName { get; set; }
    public IList<Ap21Sku> Skus { get; set; } = new List<Ap21Sku>();
}

public class Ap21Sku
{
    public int SkuIdx { get; set; }
    public string SizeCode { get; set; }
    public int SizeSequence { get; set; }
    public string Barcode { get; set; }
}

我的 ProductResult 如下所示:

public int StyleIdx { get; set; }
public int ClrIdx { get; set; }
public int SkuIdx { get; set; }
public string StyleCode { get; set; }
public string ColourCode { get; set; }
public string ColourName { get; set; }
public string SizeCode { get; set; }
public int SizeSequence { get; set; }
public string ColourTypeCode { get; set; }
public string ColourTypeName { get; set; }
public string Barcode { get; set; }
public string WebData { get; set; }

循环结果并创建 Ap21Style 模型的有效方法是什么,它们是具有 Ap21Clr 的复合对象,然后在行级别,颜色有 Ap21Sku 吗?

最佳答案

假设是这样的

List<ProductResult> products = GetPropducts();

组合样式将涉及按复合键对数据进行分组

List<Ap21Style> results = products
    .GroupBy(p => new { p.StyleIdx, p.StyleCode })
    .Select(g => new Ap21Style {
        StyleIdx = g.Key.StyleIdx,
        StyleCode = g.Key.StyleCode,
        Clrs = g.GroupBy(s => new {
            s.ClrIdx,
            s.ColourCode,
            s.ColourName,
            s.ColourTypeCode,
            s.ColourTypeName
        }).Select(g1 => new Ap21Clr {
            ClrIdx = g1.Key.ClrIdx,
            ColourCode = g1.Key.ColourCode,
            ColourName = g1.Key.ColourName,
            ColourTypeCode = g1.Key.ColourTypeCode,
            ColourTypeName = g1.Key.ColourTypeName,
            Skus = g1.Select(s => new Ap21Sku {
                Barcode = s.Barcode,
                SizeCode = s.SizeCode,
                SizeSequence = s.SizeSequence,
                SkuIdx = s.SkuIdx
            }).ToList()
        }).ToList()
    }).ToList();

关于c# - 从单个(平面)数据库查询创建复合对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45226629/

相关文章:

c# - 静态注册的工厂模式

c# - 我的引用传递没有做它应该做的事情

c# - 我们可以在 Windows 应用程序中使用 Jquery 吗?

c# - 在 C# 中使用 LINQ 进行分组 - 索引越界

c# - LINQ to SQL 为类似的分组依据表达式生成不同的查询

c# - RDLC 中的特定格式编号

c# - 如何在 C# winforms 中使用 Microsoft Excel 作为 Grid 控件?

c# - 在 LINQ 的一列上使用 distinct 获取整行

c# - LINQ 从集合 C# 返回 Dictionary<string, List<Item>>

c# - 如何按元素列表分组?