Linq使用多个标志连接两个List <t>

时间:2015-09-23 22:25:01

标签: c# linq collections

大家好今天我很困惑,尝试使用ArticleId和CellarId作为Flag加入两个List,如果两个Flags匹配则减去并显示结果。这是我的代码:

文章类:

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

我目前的结果:

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

感谢任何帮助,谢谢

1 个答案:

答案 0 :(得分:1)

当前编写代码的方式,你需要在arr1中使用ArticleQuantity为负数而不是积极的Sum()来给你预期的结果。我想这个数组代表销售量,从手头的数量中减去。

一个简单的解决方案是创建一个新版本的arr1:

var arr1Negative = arr1.Select(a => 
    new Articles() 
    { 
        ArticleId = a.ArticleId, 
        CellarId = a.CellarId, 
        ArticleQuantity = -a.ArticleQuantity
    });

并使用它代替arr1。

您也可以将类似的逻辑移动到GetArrayDifferences3D()。