C#排序IEnumerables的IEnumerable

时间:2019-12-13 09:43:14

标签: c# linq sorting

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

client.ClientCredentials.UserNamePassword.Password = password;

从本质上讲,我最终得到了一个IEnumerable的节,而这些节又包含一个IEnumerable的项。部分列表和项目都需要通过各自的SortOrder属性进行排序。

我知道我可以通过执行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; } } 对部分进行排序,但是后来我也无法弄清楚如何对每个部分中的项目进行排序。

上下文是,我正在编写一个Sort函数,该函数接受未排序的MyObj并返回带有部分和已排序项的一个。

obj.Sections.OrderBy(s => s.SortOrder)

预期的数据结构如下:

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

  return sortedObj;
}

1 个答案:

答案 0 :(得分:4)

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

// 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);
相关问题