20

我目前正在尝试找出一种使用 LINQ 和 C# 对元素进行排序的好方法,但我有点没能做到。

对于这个问题,假设您有下表

---TempTable
ID (int)
ParentID (int)
Name (varchar)
SortOrder (int)

ID 和 ParentID 相互关联,并给了我一个自我分层的数据结构。根元素在 ID 字段中有一个空值。SortOrder 只是整个表的一部分,并且基于 ParentID,因此共享相同 ParentID 的元素中确实有 1、2、3。

让我们进一步假设以下数据:

ID = 1
ParentID = null
Name = Test 1
SortOrder = 1

ID = 2
ParentID = 1
Name = Test 2
SortOrder = 1

ID = 3
ParentID = 1
Name = Test 3
SortOrder = 2

ID = 4
ParentID = 2
Name = Test 4
SortOrder = 1

我想要的平面列表应具有以下顺序:

Test 1 //root element with sort order 1 = very top
Test 2 //child element of root with sort order 1
Test 4 //child element of test 2 with sort order 1
Test 3 //child element of root with sort order 2

此外,我喜欢获取对象本身,而不仅仅是获取部分信息,而是使用 select new ...

这是我失败的尝试之一:

from x in EntityModel.TempTables //DbSet<TempTable> by EntityFramework - which already holds all elements
   orderby x.SortOrder
   from y in x.TempTableChildren //Navigation Property by EntityFramework
   orderby y.SortOrder
   select y

在此先感谢您的帮助。

编辑:

使用 ParentID 的顺序可能会有所帮助,因为 ID 和 ParentID 的顺序都是完美的,但在真实的应用程序中并非如此,因为它的数据驱动,有人可以删除一个条目,创建一个新条目并将其放置在在父母下的某些订单,你会有类似的东西:

ID = 193475037
ParentID = 2
Name = Test 192375937
SortOrder = 25

现在在应用程序中可以移动这个,ParentID 和 SortOrder 会随机更改为:

ID = 193475037
ParentID = 456798424
Name = Test 192375937
SortOrder = 4

为了进一步解释这里的问题是一些代码 - 我将如何在没有 1 美丽的 Linq Query 但有 2 和一些产量回报的情况下做到这一点:

public class LinqTestDemo
{
    Random rand = new Random();
    List<TempTable> list = new List<TempTable>();

    public List<TempTable> GetFlatData()
    {
        list = GetTestData();

        var rootElement = (from x in list
                            where x.ParentID == null
                            orderby x.SortOrder
                            select x).ToList();

        var flatList = OrderChilds(rootElement).ToList();

        foreach (var tempTable in flatList)
        {
            Console.WriteLine(string.Format("ID = {0} - ParentID = {1} - Name = {2} - SortOrder = {3}", tempTable.ID, tempTable.ParentID, tempTable.Name, tempTable.SortOrder));
        }

        return flatList;
    }

    private IEnumerable<TempTable> OrderChilds(List<TempTable> enumerable)
    {
        foreach (var tempTable in enumerable)
        {
            yield return tempTable;

            TempTable table = tempTable;
            var childs = OrderChilds((from x in list
                                        where x.ParentID == table.ID
                                        orderby x.SortOrder
                                        select x).ToList());

            foreach (var child in childs)
            {
                yield return child;
            }
        }
    }

    public List<TempTable> GetTestData()
    {
        var returnValue = new List<TempTable>();
        for (int i = 0; i < 50; i++)
        {
            var tempTable = new TempTable();
            tempTable.ID = i;
            if (i == 0)
                tempTable.ParentID = null;
            else
                tempTable.ParentID = rand.Next(0, i);

            var maxSortOrder = (from x in returnValue
                                where x.ParentID == tempTable.ParentID
                                select (int?)x.SortOrder).Max();

            if (maxSortOrder.HasValue)
                tempTable.SortOrder = maxSortOrder.Value + 1;
            else
                tempTable.SortOrder = 1;

            tempTable.Name = string.Format("Test {0:00}", i);
            returnValue.Add(tempTable);
        }

        return returnValue;
    }

    public class TempTable
    {
        public int ID { get; set; }
        public int? ParentID { get; set; }
        public string Name { get; set; }
        public int SortOrder { get; set; }
    }
}

@ Breadth-First vs Depth-First Traversal:经过一番阅读,我会说我想要的结果是 Depth-First Traversal,其中相同级别深度的元素应按属性 SortOrder 排序。

4

5 回答 5

14
  public lEnumerable<TempTable> GetList( int? parentID = null){

     foreach ( var item in Context.TempTables
        .Where( x => x.ParentID == parentID )
        .OrderBy( x=> x.SortOrder)
        .ToList() {

        yield return item;

        foreach( var child in GetList( item.ID))
        {
            yield return child;
        }

     }
  }


  var sortedList = GetList();

它类似于您的方法,但它更小且具有递归性。并且适用于许多深度级别。我更喜欢调用 ToList 因为它会在查询下一个查询之前关闭结果集。

到目前为止,无法在单个查询中执行此操作。

根据请求使用单个查询

实体框架将自动填充所有子项。

 public IEnumerable<TempTable> PrepareList(IEnumerable<TempTable> list){
     list = list.OrderBy( x=> x.SortOrder);
     foreach(var item in list){
         yield return item;
         foreach(var child in PrepareList(item.ChildTempTables)){
             yield return child;
         }
     }
 }

 // since EF will automatically fill each children on fetch
 // all we need is just a top level nodes
 // which we will pass to PrepareList method
 var list = Context.TempTables.ToList().Where(x=> x.ParentID == null);
 var sortedList = PrepareList(list).ToList();

 // it is good to create list at the end if you are going to 
 // iterate it many times and logic will not change.
于 2013-08-09T09:16:05.483 回答
4

这是一个非递归版本。它不会一次又一次地遍历初始列表。相反,它为父子关系维护一个字典,并将正在进行的前序树遍历的当前位置存储在枚举器中。

public static IEnumerable<TempTable> PreorderForest(IEnumerable<TempTable> list)
{
    var nodesByParent = list.GroupBy(x => x.ParentID.GetValueOrDefault(-1))
        .ToDictionary(xs => xs.Key, 
                      xs => xs.OrderBy(x => x.SortOrder).GetEnumerator());

    var stack = new Stack<IEnumerator<TempTable>>();
    stack.Push(nodesByParent[-1]);

    while (stack.Count > 0)
    {
        var nodes = stack.Peek();
        if (nodes.MoveNext())
        {
            yield return nodes.Current;
            IEnumerator<TempTable> children;
            if (nodesByParent.TryGetValue(nodes.Current.ID, out children))
                stack.Push(children);
        }
        else
            stack.Pop();
    }
}
于 2013-08-09T09:23:55.133 回答
4

其实我不知道它是否可以通过优雅的 LINQ 查询来实现。这是 DFS 的递归版本,它构建查找以加快搜索速度ParentID

public static IEnumerable<TempTable> SortedList(IEnumerable<TempTable> list = null, int? ParentID = null, ILookup<int?, TempTable> lookup = null)
{
    if (lookup == null)
        lookup = list.ToLookup(x => x.ParentID, x => x);

    foreach (var p in lookup[ParentID].OrderBy(x => x.SortOrder))
    {
        yield return p;
        foreach (var c in SortedList(lookup: lookup, ParentID: p.ID))
            yield return c;
    }
}
于 2013-08-09T10:15:26.460 回答
2

试试这个:

public class Item
{
    public int ID { get; set; }
    public int? ParentID { get; set; }
    public string Name { get; set; }
    public int SortOrder { get; set; }
}

public void DoWork()
    {
        Item[] data = new Item[] {
            new Item() { ID = 2, ParentID = 1, Name = "Test 2", SortOrder = 1},
            new Item() { ID = 3, ParentID = 1, Name = "Test 3", SortOrder = 2},
            new Item() { ID = 4, ParentID = 2, Name = "Test 4", SortOrder = 1},
            new Item() { ID = 1, ParentID = null, Name = "Test 1", SortOrder = 1},
        };

        var result = from x in data
                     orderby x.SortOrder, x.ParentID
                     select x;

        foreach (var row in result.ToArray())
        {
            Console.WriteLine(row.Name);
        }
    }

我想这都是关于正确的排序

于 2013-07-31T10:51:14.283 回答
2

这是一个简单的解决方案:

public class TempTable
{
    public int ID {get;set;}
    public int? ParentID {get;set;}
    public String Name {get;set;}
    public int SortOrder {get;set;}
}

public List<TempTable> GetTempData()
{
    var temp = new List<TempTable>();
    temp.Add(new TempTable { ID = 1, ParentID = null, Name = "Test 1", SortOrder = 1 });
    temp.Add(new TempTable { ID = 2, ParentID = 1, Name = "Test 2", SortOrder = 1 });
    temp.Add(new TempTable { ID = 3, ParentID = 1, Name = "Test 3", SortOrder = 3 });
    temp.Add(new TempTable { ID = 4, ParentID = 2, Name = "Test 4", SortOrder = 1 });
    temp.Add(new TempTable { ID = 5, ParentID = 1, Name = "Test 5", SortOrder = 2 });
    return temp;
}

用法:

var data = GetTempData();
var result = data.OrderBy(d => d.SortOrder).ThenBy(d => d.ParentID);
//Do something with result
于 2013-07-31T10:57:49.077 回答