简体   繁体   中英

group by and merge some field result in linq

I have a class like

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now I have a list of this class: List<Person> persons ;

var persons = new List<Person> {
            new Person { Id = 1, LastName = "Reza", FirstName="Jenabi" },
            new Person { Id = 1, LastName = "Amin", FirstName="Golmahalle"},
            new Person { Id = 2, LastName = "Hamed", FirstName="Naeemaei"}
        };

Is there a way I can group by Id and get the list of all the full Name (Combine first and last names)?

So after grouping:

var Id = results[0].Id; // Output : 1
List<string> fullNames = results[0].FullNames; // Output : "Reza Jenabi","Amin Golmahalle"

I believe this is what you need:

var results = persons.GroupBy(x => x.Id)
    .Select(x => new { Id = x.Key, FullNames = x.Select(p => $"{p.FirstName} {p.LastName}").ToList() })
    .ToList();

I think bellow code can help you:

var fff = from p in persons
        group $"{p.FirstName} {p.LastName}" by p.Id into g
        select new { PersonId = g.Key, FullNames = g.ToList() };

yeah, you can use GroupBy and Join those items:

var grouped = persons.GroupBy(p => p.Id)
    .Select(s => string.Join(", ", s.Select(a=> $"{a.FirstName} {a.LastName}")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM