I have a list in C# defined like this:
public class Author
{
public string Name { get; set; }
public string Book { get; set; }
public string Age { get; set; }
public string Address { get; set; }
}
List<Author> originalAuthorList = new List<Author>
{
new Author{ Name = "Bob", Age = "30", Address = "123 Main St.", Book = "Bob's First Book", },
new Author{ Name = "Dan", Age = "32", Address = "456 main St.", Book = "Dan's First Book" },
new Author{ Name = "Dan", Age = "32", Address = "456 main St.", Book = "Dan's Second Book" },
new Author{ Name = "Tom", Age = "34", Address = "789 main St.", Book = "Tom's First Book" }
};
How could I rearrange the list to look like this:
List<Author> newAuthorList = new List<Author>
{
new Author{ Name = "Bob", Age = "30", Address = "123 Main St.", Book = "Bob's First Book" },
new Author{ Name = "Dan", Age = "32", Address = "456 Main St.", Book = "Dan's First Book, Dan's Second Book" },
new Author{ Name = "Tom", Age = "34", Address = "789 Main St.", Book = "Tom's First Book" }
};
What I have tried:
I know that if I only had 2 fields, for example, Name and Book, I could do this:
List<Author> newAuthorList = originalAuthorList
.GroupBy(
a => a.Name,
a => a.Book)
.Select(g => new Author
{
Name = g.Key,
Book = string.Join(", ", g)
})
.ToList();
But, how would I include all 4 fields in the new list?