循环解决方案
由于我并没有真正参与 SQL 和 LINQ 分组,我们可以编写它来分发数据:
var notesByDate = new List<GroupedNoteModel>();
foreach ( var note in notesById )
{
GroupedNoteModel item = notesByDate.Find(n => n.Date == note.Date);
if ( item == null )
{
item = new GroupedNoteModel();
item.NoteWithSameDateList = new List<GroupItemModel>();
item.Date = note.Date;
notesByDate.Add(item);
}
var subitem = new GroupItemModel();
subitem.NoteID = note.NoteID;
subitem.Text = note.Text;
item.NoteWithSameDateList.Add(subitem);
}
测试
var date = DateTime.Now;
var notesById = new List<NoteModel>();
notesById.Add(new NoteModel { Date = date.AddDays(0), NoteID = 1, Text = "Note 1" });
notesById.Add(new NoteModel { Date = date.AddDays(1), NoteID = 2, Text = "Note 2" });
notesById.Add(new NoteModel { Date = date.AddDays(2), NoteID = 3, Text = "Note 3" });
notesById.Add(new NoteModel { Date = date.AddDays(0), NoteID = 4, Text = "Note 4" });
notesById.Add(new NoteModel { Date = date.AddDays(2), NoteID = 5, Text = "Note 5" });
foreach ( var item in notesByDate )
{
Console.WriteLine(item.Date);
foreach ( var note in item.NoteWithSameDateList)
{
Console.WriteLine($" {note.NoteID}: {note.Text}");
}
}
输出
21/08/2021 07:56:11
1: Note 1
4: Note 4
22/08/2021 07:56:11
2: Note 2
23/08/2021 07:56:11
3: Note 3
5: Note 5
干净的重构
除了为实体提供构造函数之外,NoteWithSameDateList 可能应该使用复合材料,否则在使用生成的分派数据时可能会出现空引用异常等问题:
Understanding the Aggregation, Association, Composition
What is the difference between association, aggregation and composition?
foreach ( var note in notesById )
{
GroupedNoteModel item = notesByDate.Find(n => n.Date == note.Date);
if ( item == null )
{
item = new GroupedNoteModel(note.Date);
notesByDate.Add(item);
}
item.NoteWithSameDateList.Add(new GroupItemModel(note.NoteID, note.Text));
}
notesById.Add(new NoteModel(date.AddDays(0), 1, "Note 1"));
notesById.Add(new NoteModel(date.AddDays(1), 2, "Note 2"));
notesById.Add(new NoteModel(date.AddDays(2), 3, "Note 3"));
notesById.Add(new NoteModel(date.AddDays(0), 4, "Note 4"));
notesById.Add(new NoteModel(date.AddDays(2), 5, "Note 5"));
public class NoteModel
{
public DateTime Date { get; set; }
public int NoteID { get; set; }
public string Text { get; set; }
public NoteModel(DateTime date, int id, string text)
{
Date = date;
NoteID = id;
Text = text;
}
}
public class GroupItemModel
{
public int NoteID { get; set; }
public string Text { get; set; }
public GroupItemModel(int id, string text)
{
NoteID = id;
Text = text;
}
}
public class GroupedNoteModel
{
public DateTime Date { get; set; }
public List<GroupItemModel> NoteWithSameDateList { get; }
public GroupedNoteModel(DateTime date)
{
NoteWithSameDateList = new List<GroupItemModel>();
Date = date;
}
}
另类
public class GroupedNoteModel
{
public DateTime Date { get; set; }
public List<GroupItemModel> NoteWithSameDateList { get; }
= new NoteWithSameDateList()
}