Ahmed Chaudhary
Ahmed Chaudhary

Reputation: 189

How can I write the following code more elegantly using LINQ query syntax?

How can I write the following code more elegantly using LINQ query syntax?

var mergedNotes = new List<Note>();

var noteGroupsByUserID = notes.GroupBy( x => x.UserID );

foreach (var group in noteGroupsByUserID)
{
    var sortedNotesByOneUser = group.OrderBy( x => x.CreatedOn ).ToList();
    var mergedNotesForAUserID = GetMergedNotesFor( sortedNotesByOneUser );
    mergedNotes.AddRange( mergedNotesForAUserID );
}

return mergedNotes;

Upvotes: 4

Views: 165

Answers (2)

Guffa
Guffa

Reputation: 700192

Not LINQ syntax, but at least more elegant...

List<Note> mergedNotes =
    notes
    .GroupBy(x => x.UserID)
    .SelectMany(g => GetMergedNotesFor(g.OrderBy(x => x.CreatedOn)))
    .ToList();

With my test data it creates the same result as your original code.

Upvotes: 5

Ronald Wildenberg
Ronald Wildenberg

Reputation: 32094

I think this does the trick:

var mergedNotes = new List<Note>();
mergedNotes.AddRange((from n in notes
                      orderby n.CreatedOn
                      group n by n.UserID into g
                      let m = GetMergedNotesFor(g)
                      select m).SelectMany(m => m));
return mergedNotes;

Upvotes: 5

Related Questions