Reputation: 51
I have an author class like this
public class Author : IEquatable<Author>
{
public string Name { get; private set; }
public List<PublicationData> Publications { get; private set };
public Author(string name, List<PublicationData> publications)
{
Name = name;
Publications = publications;
}
public override string ToString()
{
string lines = Name + "\n";
foreach (PublicationData publication in Publications)
lines += publication.ToString() + "\n";
return lines;
}
public bool Equals(Author other)
{
return Name.Equals(other.Name);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
And I have publication class like this
public class PublicationData : IEquatable<PublicationData>
{
public string Code { get; set; }
public int Amount { get; set; }
public int Subscription_Length { get; set; }
public PublicationData(string name, int amount, int subscription_Length)
{
Code = name;
Amount = amount;
Subscription_Length = subscription_Length;
}
public override string ToString()
{
return String.Format($"{Code}, {Amount}, {Subscription_Length}");
}
public bool Equals(PublicationData other)
{
return Code.Equals(other.Code);
}
public override int GetHashCode()
{
return Code.GetHashCode();
}
}
Then I have a list of authors that look like this:
AuthorA - PublicationA
AuthorB - PublicationB
AuthorB - PublicationC
I want to get something like this as a new object:
AuthorA - PublicationA
AuthorB - PublicationB - PublicationC
I assume the code should look something like this:
var filtered = authors.Select(nn => new Author
(
nn.Name,
// merge publication lists
)).Distinct()
.ToList();
I just have no idea how do I do this. Can anyone suggest something?
Upvotes: 1
Views: 84
Reputation: 3767
You can also achieve it via the following code.
var query = from author in authors
group author by author.AuthorName;
foreach (var group in query)
{
Console.WriteLine(group.Key);
// Nested foreach is required to access group items.
foreach (var g in group)
{
Console.WriteLine($"\t{g.Publication}");
}
}
Here is a document Group query results you can refer to.
Upvotes: 1
Reputation: 143373
It seems that you are looking for GroupBy
method:
authors
.GroupBy(a => a.Name)
.Select(g => new Author(
g.Key,
g.SelectMany(ga => ga.Publications).ToList()))
Upvotes: 4