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

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

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

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 to objects,您可以使用 moreLinq library

它有一个 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 });