繁体   English   中英

C# Net Core 将2个列表与Linq进行比较并新建一个

[英]C# Net Core Compare 2 List with Linq and Create New One

我正在使用 .NET Core 6、SQL 服务器和 Oracle 数据库。 我创建了 2 个 object 类型的通用列表。 所有列表都包含同类信息。

Line、MaterialName、MaterialId 和 MaterialCount 信息,我没有 id 信息。 我无法加入

var productList = new List<object>(); // **used elements**
var reportList = new List<object>();  // **must be used elements**

我有 4 条线和 20 种材料。 reportList有 40 个元素, productList有 21 个。

我需要计算材料的百分位数。 我需要将装配线中使用的材料与使用的材料按百分比进行比例分配。 下面的示例应该使用 2500 个主板,但看起来使用了 2000 个。 所以 100 * 2000 / 2500 = 80。所以效率是 80%。

例子:

  reportList element                                     productList element

  {                                                      {
    "materialId": 1,                                            "materialId": 1,
    "line": "Line1",                                            "line": "Line1",
    "materialName": "Mainboard",                                "materialName": "Mainboard",
    "materialCount": 2500                                       "materialCount": 2000
  },                                                      },

最终列表元素必须是:

{  
    "materialId": 1,
    "line": "Line1",
    "materialName": "Mainboard",
    "materialCount": 80
},

如果从未使用过产品,则不会在产品列表中productlist 百分比数将自动为 0。(因此 materialCount 必须为 0。materialCount = 0)。 所以最终的列表元素计数将与 reportList 相同。

什么不起作用? 它们是简单的通用列表。 后 ”。” 符号,我们不能使用任何信息,因为它们是列表。 我无法输入 something is equal to something。 我们需要一些不同的东西...

*from report in reportList

join product in productList
on report.Line equals generalRule.Line* 

假设,您正在使用 Linq 对象,您可以使用moreLinq 库

它有一个LeftJoin扩展方法。

class Element
{
    public int materialId { get; set; }
    public string line { get; set; }
    public string materialName { get; set; }
    public double materialCount { get; set; } // Must be double here for the calculation to work
}
var productList = new List<Element>(); // **used elements**
var reportList = new List<Element>();  // **must be used elements**

var result = reportList
    .LeftJoin(
        productList,
        // Join by materialId, line and materialName
        r => new { materialId = r.materialId, line = r.line, materialName = r.materialName },
        // No element in productList found, materialCount will be 0
        r => new Element {materialId = r.materialId, line = r.line, materialName = r.materialName }, 
        // An element in productList was found => do the calculation
        (r, p) => new Element {materialId = r.materialId, line = r.line, materialName = r.materialName, materialCount = 100 * p.materialCount / r.materialCount }); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM