У меня есть простая настройка (ниже). Каждая «сборка» содержит список деталей. Внутри сборки могут повторяться объекты «Деталь».
Моя цель - объединить объекты детали (по идентификатору) и суммировать количества.
Конечный результат должен выглядеть следующим образом (где суммы для каждой части суммировались):
[Assembly 1]
[3] Part 1
[8] Part 2
[4] Part 3
[Assembly 2]
[3] Part 1
[15] Part 3
Посмотрите код ниже в разделе «ВЫХОД КОНСОЛИ» для того, что я в настоящее время получаю.
Я пробовал следующее LINQ (не удалось):
List<Assembly> listAssy2 = listAssy.SelectMany(a => a.listParts.GroupBy(b => b.qty)).ToList();
Код:
public class Part {
public int id { get; set;}
public string title { get; set; }
public int qty { get; set; }
}
public class Assembly {
public int id { get; set; }
public string title { get; set; }
public List<Part> listParts { get; set; }
}
public static void Main()
{
List<Assembly> listAssy = new List<Assembly>();
// ----------------- ASSEMBLY 1 -----------------
//List of Parts
List<Part> partList1 = new List<Part>();
partList1.Add(new Part { id = 1, title = "Part 1", qty = 2 });
partList1.Add(new Part { id = 1, title = "Part 1", qty = 1 });
partList1.Add(new Part { id = 2, title = "Part 2", qty = 2 });
partList1.Add(new Part { id = 3, title = "Part 3", qty = 4 });
partList1.Add(new Part { id = 2, title = "Part 2", qty = 6 });
Assembly assy1 = new Assembly {id = 1, title = "Assembly 1", listParts = partList1};
listAssy.Add(assy1);
// ----------------- ASSEMBLY 2 -----------------
//List of Parts
List<Part> partList2 = new List<Part>();
partList2.Add(new Part { id = 1, title = "Part 1", qty = 2 });
partList2.Add(new Part { id = 3, title = "Part 3", qty = 4 });
partList2.Add(new Part { id = 3, title = "Part 3", qty = 11 });
partList2.Add(new Part { id = 1, title = "Part 1", qty = 1 });
Assembly assy2 = new Assembly {id = 2, title = "Assembly 2", listParts = partList2};
listAssy.Add(assy2);
foreach (var assy in listAssy) {
Console.WriteLine("[" + assy.title + "]");
foreach (var part in assy.listParts) {
Console.WriteLine(" [" + part.qty + "] " + part.title);
}
Console.WriteLine("");
}
/* ***** CONSOLE OUTPUT ******
[Assembly 1]
[2] Part 1
[1] Part 1
[2] Part 2
[4] Part 3
[6] Part 2
[Assembly 2]
[2] Part 1
[4] Part 3
[11] Part 3
[1] Part 1
*/
}