class GroupedItem
{
public string A { get; set; }
public string B { get; set; }
public int TotalC { get; set; }
}
class Program
{
static void Main()
{
List<GroupedItem> list1 = new List<GroupedItem>
{
new GroupedItem { A = "A1", B = "B1", TotalC = 10 },
new GroupedItem { A = "A2", B = "B2", TotalC = 15 },
new GroupedItem { A = "A3", B = "B3", TotalC = 20 }
};
List<GroupedItem> list2 = new List<GroupedItem>
{
new GroupedItem { A = "A1", B = "B1", TotalC = 10 },
new GroupedItem { A = "A2", B = "B2", TotalC = 16 },
new GroupedItem { A = "A4", B = "B4", TotalC = 25 }
};
var groupedAndSelected1 = list1.GroupBy(item => new { item.A, item.B })
.Select(group => new GroupedItem
{
A = group.Key.A,
B = group.Key.B,
TotalC = group.Sum(item => item.TotalC)
});
var groupedAndSelected2 = list2.GroupBy(item => new { item.A, item.B })
.Select(group => new GroupedItem
{
A = group.Key.A,
B = group.Key.B,
TotalC = group.Sum(item => item.TotalC)
});
var result = CompareGroupedItems(groupedAndSelected1.ToList(), groupedAndSelected2.ToList());
Console.WriteLine("Added items:");
foreach (var item in result.AddedItems)
{
Console.WriteLine($"A={item.A}, B={item.B}, TotalC={item.TotalC}");
}
Console.WriteLine("Removed items:");
foreach (var item in result.RemovedItems)
{
Console.WriteLine($"A={item.A}, B={item.B}, TotalC={item.TotalC}");
}
}
static (List<GroupedItem> AddedItems, List<GroupedItem> RemovedItems) CompareGroupedItems(List<GroupedItem> list1, List<GroupedItem> list2)
{
var addedItems = list1.Except(list2, new GroupedItemComparer()).ToList();
var removedItems = list2.Except(list1, new GroupedItemComparer()).ToList();
return (addedItems, removedItems);
}
}
class GroupedItemComparer : IEqualityComparer<GroupedItem>
{
public bool Equals(GroupedItem x, GroupedItem y)
{
if (x == null || y == null)
return false;
return x.A == y.A && x.B == y.B && x.TotalC == y.TotalC;
}
public int GetHashCode(GroupedItem obj)
{
return (obj.A + obj.B + obj.TotalC).GetHashCode();
}
}
留言
張貼留言