【问题标题】:C# Sorting IEnumerable of IEnumerablesC# 对 IEnumerable 的 IEnumerable 进行排序
【发布时间】:2019-12-13 09:43:14
【问题描述】:

我有一个看起来像这样的对象:

public class MyObj 
{
  public string Title { get; set; }
  public IEnumerable<Section> Sections { get; set; }
}

public class Section
{
  public string Title { get; set; }
  public IEnumerable<Item> Items { get; set; }
  public int SortOrder { get; set; }
}

public class Item
{
  public string Title { get; set; }
  public int SortOrder { get; set; }
}

基本上,我最终得到一个 IEnumerable 部分,而这些部分又包含一个 IEnumerable 项目。部分列表和项目都需要按其各自的 SortOrder 属性进行排序。

我知道我可以通过 obj.Sections.OrderBy(s =&gt; s.SortOrder) 对部分进行排序,但是我也不知道如何对每个部分中的项目进行排序。

上下文是我正在编写一个 Sort 函数,它接受一个未排序的 MyObj 并返回一个同时包含已排序的部分和项目。

public MyObj Sort(MyObj unsortedObj)
{
  var sortedObj = unsortedObj.....

  return sortedObj;
}

预期的数据结构是这样的:

- Section1
  - Item1
  - Item2
- Section2
  - Item1
  - Item2

【问题讨论】:

  • obj.Sections.OrderBy(s =&gt; s.SortOrder) 不会排序 Sections 它将返回新的 IOrderedEnumerable
  • 这里的预期结果是什么?您希望Items 在每个Section 中排序还是对所有MyObj 排序?
  • @PavelAnikhouski 更新为预期排序
  • 我们不能先对section中的所有item进行排序,然后再对section本身进行排序吗? @SamWalpole

标签: c# linq sorting


【解决方案1】:

您可以方便地添加创建这些对象副本的方法,但一个属性不同:

// in MyObj
public MyObj WithSections(IEnumerable<Section> sections) =>
    new MyObj {
        Title = this.Title,
        Sections = sections
    };

// in Section
public Section WithItems(IEnumerable<Items> items) =>
    new Section {
        Title = this.Title,
        Items = items,
        SortOrder = this.SortOrder
    };

首先,对部分进行排序

var sortedSections = unsortedObj.Sections.OrderBy(x => x.SortOrder);

然后对于每个已排序的部分,使用Select 转换它们,以便它们的项目也被排序:

var sortedSectionsAndItems = sortedSections.Select(x => x.WithItems(x.Items.OrderBy(y => y.SortOrder)));

现在您可以返回带有已排序部分和项目的MyObj

return unsortedObj.WithSections(sortedSectionsAndItems);

【讨论】:

  • 非常感谢。我所做的唯一修改是使方法成为静态扩展。即public static MyObj WithSections(this MyObj obj, IEnumerable&lt;Section&gt; sections)....
猜你喜欢
  • 2014-10-14
  • 2011-04-07
  • 2012-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多