如何使用LINQ查询语法更优雅地编写以下代码?
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;
答案 0 :(得分:5)
我认为这就是诀窍:
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;
答案 1 :(得分:5)
不是LINQ语法,但至少更优雅...
List<Note> mergedNotes =
notes
.GroupBy(x => x.UserID)
.SelectMany(g => GetMergedNotesFor(g.OrderBy(x => x.CreatedOn)))
.ToList();
使用我的测试数据,它会创建与原始代码相同的结果。