【问题标题】:How to distribute a list of objects in a new reorganized list of objects having an embedded list in order to change the root primary key/index?如何在具有嵌入列表的新重组对象列表中分发对象列表以更改根主键/索引?
【发布时间】:2021-08-21 04:33:51
【问题描述】:

我想将 NoteModel 对象列表转换为对象列表,如下所示。

最终结果应包含包含日期的 GroupNoteModels 对象列表和具有相应日期的 GroupItemModel 对象列表。

public class NoteModel
{
    public DateTime Date { get; set; }
    public int NoteID { get; set; }
    public string Text { get; set; }
}

初始化并添加注释到noteList

private List<NoteModel> noteList = new List<NoteModel>();

public void AddNotes()
{
    aodList.Add(new AODModel(DateTime.Now, 1, "Text1"));
    aodList.Add(new AODModel(DateTime.Now.AddDays(1), 2, "Text2"));
    aodList.Add(new AODModel(DateTime.Now.AddDays(1), 3, "Text3"));
}

用于列表列表的模型

public class GroupItemModel
{
    public int NoteID { get; set; }
    public string Text { get; set; }
}

public class GroupedNoteModel
{
    public DateTime Date { get; set; }
    public List<GroupItemModel> noteWithSameDateList { get; set; }
}

我尝试过的代码

var noteGrouped = noteList.GroupBy(a => a.Date )
                    .Select(a => new
                    {
                        Date= a.Select(x=>x.Date ),
                        noteWithSameDateList= new {
                            NoteID = a.Select(x=>x.NoteID ),
                            Text= a.Select(x => x.Text)
                        } 
                    }).ToList();

List<GroupedNoteModel> noteGroupList = noteGrouped;

【问题讨论】:

    标签: c# linq object model grouping


    【解决方案1】:

    循环解决方案

    由于我并没有真正参与 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()
    }
    

    【讨论】:

      【解决方案2】:

      groupby 操作的输出类似于“分组列表”,而分组类似于“原始对象列表加上它们共享相同的 Key 属性”

      所以作为一个更简单的例子

        [
          {name:John, age:23},
          {name:Jim,  age:23},
          {name:Jack, age:24}
        ]
      

      “按年龄分组”产生

      [
        {Key: 23, [{name:John, age:23},{name:Jim,  age:23}]},
        {Key: 24, [{name:Jack, age:24}]},
      ]
      

      在“JSON”中表示有点困难,因为 Grouping(具有 Key 属性的对象)is-a list,而不是 has-a list

      因此,总而言之,“按 X.Y 分组的 X 列表产生分组列表,并且分组本身是 X 列表和 Key-of-same-X.Y”

      在您的代码中:

      var noteGrouped = noteList.GroupBy(a => a.Date )
                          .Select(a => new
                          {
                              Date= a.Select(x=>x.Date ),
                              noteWithSameDateList= new {
                                  NoteID = a.Select(x=>x.NoteID ),
                                  Text= a.Select(x => x.Text)
                              } 
                          }).ToList();
      
      List<GroupedNoteModel> noteGroupList = noteGrouped;
      

      我发现最好始终仔细考虑如何调用 lambda 的参数 - 在这两种情况下,您都将您的参数称为“a”,但一种是 NoteModel,一种是 Grouping。请记住,您的分组是“可使用 Key 属性进行枚举的,这是分组的内容/它们都共享的内容,即在您的情况下为 DateTime”

      对于初学者,这意味着您的 groupby 中应该有“note”或“n”(因为它在 NoteModels 上运行),在您的第一个选择中应该有“grp”或“g”(因为在 Groupings 上运行,它们是列表NoteModels)

      输出模型中的 Date 属性也绝对应该是分组的关键

      NoteWithSameDate 应该是“笔记列表”(分组是什么)到“groupitemmodel 列表”的转换

      var noteGrouped = noteList
          .GroupBy(n => n.Date ) //n is a NoteModel
          .Select(grp => new GroupedNoteModel() //you'd made an anonymous type here when you wanted to make one of these
              { 
                  Date = grp.Key,
                  noteWithSameDateList= grp.Select(note => //grp is a "list" of NoteModel. 'note' here is a single notemodel
                      new GroupItemModel() //not an anonymous type
                      {
                          NoteID = note.NoteId,
                          Text= note.Text
                      }
                  ).ToList() //turn.   grp.Select(note...   into a list
              }
          ).ToList(); //turn.  .Select(grp...   into a list
      

      最后一个小提示,在前面的答案中,我谈到了 groupby 的输出是一个分组列表,而 grouping 是一个原始对象的列表。我通俗地使用术语列表来指代一些可枚举的集合;它不是字面上的List&lt;IGrouping&gt; 和 IGrouping 也不是字面上的List&lt;T&gt; - 它只是更容易理解短语“列表列表”而不是组中涉及的疯狂数量的泛型类型(“一个可枚举的可枚举的 igroupings")

      还有其他更复杂的 GroupBy 重载;他们自己使用 lambdas 将输入对象直接转换为输出,而无需后续 Select 操作,但我建议您围绕简单的“按日期分组,获取具有相同日期的列表”现在..

      【讨论】:

      • 感谢您的解释和回答
      猜你喜欢
      • 1970-01-01
      • 2018-01-28
      • 2017-08-30
      • 2011-02-11
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      • 1970-01-01
      相关资源
      最近更新 更多