c# Merging 3 collection list into one list
.net, c#, linq
Solution
Try this:
English.Select(t => new Tuple<Thing,int>(t, 1)).Concatenate(
German.Select(t => new Tuple<Thing,int>(t, 2)).Concatenate(
Spanish.Select(t => new Tuple<Thing,int>(t, 3))
)
).GroupBy(p => p.Item1.ID)
.Select(g => new {
Id = g.Key
, English = g.Where(t => t.Item2==1).Select(t => t.Item2.Stuff).SingleOrDefault()
, German = g.Where(t => t.Item2==2).Select(t => t.Item2.Stuff).SingleOrDefault()
, Spanish = g.Where(t => t.Item2==3).Select(t => t.Item2.Stuff).SingleOrDefault()
});
The idea is to tag the original items with their collection origin (`1` for English, `2` for German, `3` for Spanish), group them by ID, and then pull the details for individual languages using the tag that we added in the first step.
Problem
I have 3 collection list as below. ``` public static List<Thing> English = new List<Thing> { new Thing {ID = 1, Stuff = "one"}, new Thing {ID = 2, Stuff = "two"}, new Thing {ID = 3, Stuff = "three"} }; public static List<Thing> Spanish = new List<Thing> { new Thing {ID = 1, Stuff = "uno"}, new Thing {ID = 2, Stuff = "dos"}, new Thing {ID = 3, Stuff = "tres"}, new Thing {ID = 4, Stuff = "cuatro"} }; public static List<Thing> German = new List<Thing> { new Thing {ID = 1, Stuff = "eins"}, new Thing {ID = 2, Stuff = "zwei"}, new Thing {ID = 3, Stuff = "drei"} }; ``` During runtime, the length of the list may vary. For eg, German may take 5 values, english with 2 and spanish with one. I need to find which list has the max value and need to get the output in the below format. ``` Id English German Spanish 1 one eins uno 2 two zwei dos 3 three drei tres 4 cuatro ``` Can you please help me to solve this.