Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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;
like image 430
Ahmed Chaudhary Avatar asked Dec 30 '22 00:12

Ahmed Chaudhary


2 Answers

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.

like image 99
Guffa Avatar answered Jan 01 '23 15:01

Guffa


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;
like image 39
Ronald Wildenberg Avatar answered Jan 01 '23 15:01

Ronald Wildenberg