简体   繁体   中英

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;

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM