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
classPerson{
publicint Id { get; set; }
publicstring Name { get; set; }
publicint Age { get; set; }
}
// example list of personsList<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 Selectvar 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 personsforeach (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: 60Id: 2, Names: Jane, Total age: 30