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;
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With