tags:

views:

120

answers:

2

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;
+4  A: 

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;
Ronald Wildenberg
Thanks, the selected answer seemed more readable to me.
Ahmed Chaudhary
+4  A: 

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.

Guffa