Suppose we have a list of objects like this:
main.cs466 chars14 lines
To merge objects with the same Id
and create a new List
with merged objects, we can use LINQ as follows:
main.cs222 chars9 lines
Explanation:
GroupBy
to group objects in the list by their Id
.Select
to create a new object for each group, where the Id
is the key of the group, and the IdsToMerge
list is a flattened list of all IdsToMerge
lists in the group using SelectMany
.ToList
to create a new List
of merged objects.The resulting mergedObjects
list would look like this:
main.cs123 chars6 lines
gistlibby LogSnag