我有两个包含两个字段的列表。我事先并不知道哪一个更大。
我想实现这个目标:
newList oldList
Fruit Qty Diff Fruit Qty
--------------------------------------------
apple 3 +1 apple 2
-2 pear 2
peach 4 +3 peach 1
melon 5 0 melon 5
coconut 2 +2
mango 4 0 mango 4
banana 2 -1 banana 3
lychi 1 +1
-3 pineapple 3
左边的一个你可以看到oldList右边的newList。如果我将oldList与newList进行比较,我希望看到两个列表中每个可能的行和数量的差异。
我写了这个,这会给我两个列表中没有包含的水果(xor)
var difference = newList.Select(x => x.Fruit)
.Except(oldList.Select(x => x.Fruit))
.ToList()
.Union(oldList.Select(x => x.Fruit)
.Except(newList.Select(x => x.Fruit))
.ToList());
但我也失去了如何将它与数量相结合。
答案 0 :(得分:3)
我没有看到LINQ表现良好且可读的方法。我更喜欢混合使用LINQ和循环:
var oldGrouped = oldList.ToDictionary(x => x.Fruit, x => x.Qty);
var newGrouped = newList.ToDictionary(x => x.Fruit, x => x.Qty);
var result = new List<FruitSummary>();
foreach(var oldItem in oldGrouped)
{
int newQuantity;
newGrouped.TryGetValue(oldItem.Key, out newQuantity)
var summary = new FruitSummary { OldFruit = oldItem.Key, OldQty = oldItem.Value };
if(newQuantity != 0)
{
summary.NewFruit = oldItem.Key;
summary.NewQty = newQuantity;
}
summary.Diff = oldItem.Value - newQuantity;
newGrouped.Remove(oldItem.Key);
result.Add(summary);
}
foreach(var newItem in newGrouped)
{
result.Add(new FruitSummary { Diff = -newItem.Value,
NewFruit = newItem.Key,
NewQty = newItem.Value });
}
班级FruitSummary
如下所示:
public class FruitSummary
{
public string OldFruit { get; set; }
public string NewFruit { get; set; }
public int OldQty { get; set; }
public int NewQty { get; set; }
public int Diff { get; set; }
}
答案 1 :(得分:2)
我假设您有Fruit
这样的课程:
public class Fruit
{
public string Name {get; set;}
public int Quantity {get; set;}
}
你有一个旧的和新的列表,如这些
List<Fruit> oldList = ...
List<Fruit> newList = ...
然后这个LINQ monstrum完成了这项工作,虽然它可能不是最高效的解决方案(但有多少种水果?):
var result =
oldList.Join(newList,
oldFruit => oldFruit.Name,
newFruit => newFruit.Name,
(oldFruit, newFruit) => new {
Name = oldFruit.Name,
Diff = oldFruit.Quantity - newFruit.Quantity}).
Concat(oldList.
Where(oldFruit => newList.All(newFruit => newFruit.Name != oldFruit.Name)).
Select(oldFruit => new {
Name = oldFruit.Name,
Diff = -oldFruit.Quantity})).
Concat(newList.Where(newFruit => oldList.All(oldFruit => oldFruit.Name != newFruit.Name)).
Select(newFruit => new {
Name = newFruit.Name,
Diff = newFruit.Quantity}));
您可以输出如下结果:
Console.WriteLine(string.Join(Environment.NewLine, result.Select(r => $"{r.Name} {r.Diff}")));
请注意,我想出了这个,因为我喜欢linq&#34;一个衬里&#34;,但使用foreach
似乎更可读,甚至可能比这个查询更快。
答案 2 :(得分:0)
这样的东西?
var difference = newList
.Concat(oldList.Select(x => new { x.Fruit, Qty = -x.Qty }))
.GroupBy(x => x.Fruit)
.Select(g => new {Fruit = g.Key, Qty = g.Sum(x => x.Qty) });
当我运行foreach(var d in difference) Console.WriteLine(d);
时,我得到:
{ Fruit = apple, Qty = 1 }
{ Fruit = peach, Qty = 3 }
{ Fruit = melon, Qty = 0 }
{ Fruit = coconut, Qty = 2 }
{ Fruit = mango, Qty = 0 }
{ Fruit = banana, Qty = -1 }
{ Fruit = lychi, Qty = 1 }
{ Fruit = pear, Qty = -2 }
{ Fruit = pineapple, Qty = -3 }