Jason Drushel
Jason Drushel

Reputation: 19

Merging objects in List<Object> on two properties

public class Note
{
    public string account;
    public DateTime noteDate;
    public string noteText;
}

List<Note> List1;

Using LINQ I'm looking for a way to combine noteText where account and noteDate are the same. For example, if the incoming list has three objects:

List1[0] = "1234", 2017-10-03, "This is a"
List1[1] = "1234", 2017-10-03, " sample note."
List1[2] = "4321", 2017-10-03, "This is another note."

I would expect the new list to have two objects:

List2[0] = "1234", 2017-10-03, "This is a sample note."
List2[1] = "4321", 2017-10-03, "This is another note."

Upvotes: 0

Views: 67

Answers (1)

D Stanley
D Stanley

Reputation: 152644

The simplest way is to group by date and account, then Join the string fields:

List2 = List1.GroupBy(n => new {n.noteDate, n.account})
             .Select(g => new Note {
                 noteDate = g.Key.noteDate,
                 account  = g.Key.account,
                 noteText = string.Join("", g.Select(n => n.noteText))
                 });

Upvotes: 5

Related Questions