Linq join两个List使用多个标志
本文关键字:标志 join 两个 List Linq | 更新日期: 2023-09-27 18:14:10
大家好,今天我很困惑,试图使用ArticleId和CellarId作为标志加入两个列表,如果两个标志匹配,然后减去并显示结果。这是我的代码:
文章类:
public class Articles
{
public Int32 ArticleId { get; set; }
public Int32 CellarId { get; set; }
public Double ArticleQuantity { get; set; }
}
数组数据和显示结果:
List<Articles> arr1 = new List<Articles>();
arr1.Add(new Articles { ArticleId = 1, CellarId = 2, ArticleQuantity = 10.50 });
arr1.Add(new Articles { ArticleId = 2, CellarId = 2, ArticleQuantity = 5.00 });
arr1.Add(new Articles { ArticleId = 5, CellarId = 1, ArticleQuantity = 2.00 });
arr1.Add(new Articles { ArticleId = 1, CellarId = 1, ArticleQuantity = 4.00 });
List<Articles> arr2 = new List<Articles>();
arr2.Add(new Articles { ArticleId = 5, CellarId = 2, ArticleQuantity = 1.00 });
arr2.Add(new Articles { ArticleId = 3, CellarId = 2, ArticleQuantity = 0.50 });
arr2.Add(new Articles { ArticleId = 1, CellarId = 1, ArticleQuantity = 5.00 });
foreach (var a in GetArrayDifferences3D(arr1, arr2))
{
Console.WriteLine("ArticleId: {0}, CellarId: {1}, Qty: {2}",
a.ArticleId, a.CellarId, a.ArticleQuantity);
}
使用linq函数连接:
public static List<Articles> GetArrayDifferences3D(
List<Articles> Array1,
List<Articles> Array2)
{
List<Articles> ArrayDifferences = new List<Articles>();
ArrayDifferences = Array1.Concat(Array2)
.GroupBy(g => new { g.ArticleId, g.CellarId })
.Select(s => new Articles
{
ArticleId = s.Select(articles => articles.ArticleId).First(),
CellarId = s.Select(cellars => cellars.CellarId).First(),
ArticleQuantity = (s.Select(a => a.ArticleQuantity).Sum())
}).ToList();
return ArrayDifferences;
}
我需要返回这个结果:
ArticleId: 1, CellarId: 2, Qty: -10.50
ArticleId: 2, CellarId: 2, Qty: -5.00
ArticleId: 5, CellarId: 1, Qty: -2.00
ArticleId: 1, CellarId: 1, Qty: 1.00
ArticleId: 5, CellarId: 2, Qty: 1.00
ArticleId: 3, CellarId: 2, Qty: 0.50
My Current result:
ArticleId: 1, CellarId: 2, Qty: 10.5
ArticleId: 2, CellarId: 2, Qty: 5
ArticleId: 5, CellarId: 1, Qty: 2
ArticleId: 1, CellarId: 1, Qty: 9
ArticleId: 5, CellarId: 2, Qty: 1
ArticleId: 3, CellarId: 2, Qty: 0.5
任何帮助都是感激的,谢谢
当前编写代码的方式,您需要arr1中的ArticleQuantity为负而不是为Sum()为您提供预期的结果。
一个简单的解决方案是创建一个新版本的arr1:
var arr1Negative = arr1.Select(a =>
new Articles()
{
ArticleId = a.ArticleId,
CellarId = a.CellarId,
ArticleQuantity = -a.ArticleQuantity
});
,用它来代替arr1。
您也可以将类似的逻辑移动到GetArrayDifferences3D()中。