【发布时间】:2013-12-31 00:35:45
【问题描述】:
这个想法是为任何树状列表(具有示例中列出的父子结构)的子项(子项的子项等)进行排序的扩展方法。 还有一点很重要,要排序的属性只有在运行时才知道(列表本身也是如此)。
扩展方法应该有类似这个签名的东西:
public static IEnumerable<T> OrderChildren<T>(
this IEnumerable<T> source,
Func<T, IEnumerable<T>> childrenSelector,
Func<T, string> orderSelector)
{
...
}
这是创建列表的示例类:
public class Example
{
public IEnumerable<Example> Children;
public string Name;
public int Id;
public Example Parent;
}
还有一些模拟数据:
{
...
var collection = MockUp();
...
}
private static IEnumerable<Example> MockUp()
{
var rootCollection = new List<Example>();
var firstLevelCollectionA = new List<Example>();
var firstLevelCollectionB = new List<Example>();
var secondLevelCollectionAA = new List<Example>();
var secondLevelCollectionAB = new List<Example>();
var secondLevelCollectionBA = new List<Example>();
var secondLevelCollectionBB = new List<Example>();
secondLevelCollectionAA.Add(new Example() {Name = "SecondLvlAA1"});
secondLevelCollectionAA.Add(new Example() {Name = "SecondLvlAA2"});
secondLevelCollectionAB.Add(new Example() {Name = "SecondLvlAB1"});
secondLevelCollectionAB.Add(new Example() {Name = "SecondLvlAB2"});
secondLevelCollectionBA.Add(new Example() {Name = "SecondLvlBA1"});
secondLevelCollectionBA.Add(new Example() {Name = "SecondLvlBA2"});
secondLevelCollectionBB.Add(new Example() {Name = "SecondLvlBB1"});
secondLevelCollectionBB.Add(new Example() {Name = "SecondLvlBB2"});
firstLevelCollectionA.Add(new Example() {Name = "FirstLvlA1", Children = secondLevelCollectionAA});
firstLevelCollectionA.Add(new Example() {Name = "FirstLvlA2", Children = secondLevelCollectionAB});
firstLevelCollectionB.Add(new Example() {Name = "FirstLvlB1", Children = secondLevelCollectionBA});
firstLevelCollectionB.Add(new Example() {Name = "FirstLvlB2", Children = secondLevelCollectionBB});
rootCollection.Add(new Example() {Name = "Root1", Children = firstLevelCollectionA});
rootCollection.Add(new Example() {Name = "Root2", Children = firstLevelCollectionB});
return rootCollection;
}
然后我们需要调用扩展方法OrderChildren,像这样:
collection.OrderChildren(x => x.Children, x => x.Name)
那么对这个扩展方法的主体有什么建议吗?
【问题讨论】:
-
+1 表示即用型代码,但您也应该展示第一次尝试。
标签: c# linq generics tree extension-methods