linq for list of objects merge object with the same id to have internal list of ids as a one list in csharp

Suppose we have a list of objects like this:

main.cs
public class ObjectToMerge
{
    public int Id { get; set; }
    public List<int> IdsToMerge { get; set; }
}

List<ObjectToMerge> objectsToMerge = new List<ObjectToMerge>()
{
    new ObjectToMerge() { Id = 1, IdsToMerge = new List<int> { 2, 3 } },
    new ObjectToMerge() { Id = 2, IdsToMerge = new List<int> { 4, 5 } },
    new ObjectToMerge() { Id = 1, IdsToMerge = new List<int> { 6 } },
    new ObjectToMerge() { Id = 3, IdsToMerge = new List<int> { 7, 8 } }
};
466 chars
14 lines

To merge objects with the same Id and create a new List with merged objects, we can use LINQ as follows:

main.cs
List<ObjectToMerge> mergedObjects = objectsToMerge
    .GroupBy(x => x.Id)
    .Select(g => new ObjectToMerge()
    {
        Id = g.Key,
        IdsToMerge = g.SelectMany(x => x.IdsToMerge).ToList()
    })
    .ToList();
222 chars
9 lines

Explanation:

  • We use GroupBy to group objects in the list by their Id.
  • We use 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.
  • Finally, we call ToList to create a new List of merged objects.

The resulting mergedObjects list would look like this:

main.cs
[
    { Id = 1, IdsToMerge = { 2, 3, 6 } },
    { Id = 2, IdsToMerge = { 4, 5 } },
    { Id = 3, IdsToMerge = { 7, 8 } }
]
123 chars
6 lines

gistlibby LogSnag