how te merge elements with linq if id is the same in csharp

You can use GroupBy to group the elements by the id property and then use Select to merge the elements with the same id. Here's an example:

main.cs
class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

// example list of persons
List<Person> persons = new List<Person>()
{
    new Person() { Id = 1, Name = "John", Age = 25 },
    new Person() { Id = 2, Name = "Jane", Age = 30 },
    new Person() { Id = 1, Name = "Jack", Age = 35 }
};

// group persons by id and merge with Select
var mergedPersons = persons
    .GroupBy(p => p.Id)
    .Select(g => new Person()
    {
        Id = g.Key,
        Name = string.Join(", ", g.Select(p => p.Name)),
        Age = g.Sum(p => p.Age)
    });

// iterate over the merged persons
foreach (var person in mergedPersons)
{
    Console.WriteLine($"Id: {person.Id}, Names: {person.Name}, Total age: {person.Age}");
}
774 chars
31 lines

Output:

main.cs
Id: 1, Names: John, Jack, Total age: 60
Id: 2, Names: Jane, Total age: 30
74 chars
3 lines

gistlibby LogSnag