繁体   English   中英

C# 对 IEnumerables 的 IEnumerable 进行排序

[英]C# Sorting IEnumerable of IEnumerables

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

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 => s.SortOrder)对部分进行排序,但是我也无法弄清楚如何对每个部分中的项目进行排序。

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

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

  return sortedObj;
}

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

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

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

// 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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