LINQ根据子顺序对平面列表进行排序

本文关键字:列表 排序 平面 顺序 LINQ | 更新日期: 2023-09-27 18:25:34

我目前正试图找到一种用LINQ和C#对元素进行排序的好方法,但我有点失败了。

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

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

ID和ParentID相互关联,给了我一个自层次的数据结构。根元素在ID字段中有一个null。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的顺序可能很有用,因为有了给定的TestData,ParentID就有了完美的顺序,但在真正的实时应用程序中却不是这样,因为它是数据驱动的,有人可以删除一个条目,创建一个新条目,并将其按特定顺序放在父项下,你会得到这样的结果:

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

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

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

为了更进一步地解释这个问题,这里有一些代码-如果没有1个漂亮的Linq查询,但有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; }
    }
}

@宽度优先与深度优先导线:经过一些阅读,我想说我想要的结果是深度优先遍历,其中相同级别深度的元素应该按照属性SortOrder排序。

LINQ根据子顺序对平面列表进行排序

  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.

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

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();
    }
}

实际上我不知道它是否可以由优雅的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;
    }
}

试试这个:

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

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

这里有一个简单的解决方案:

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