gpt4 book ai didi

c# - 使用单链接实体列表的 Linq 中的自定义 OrderBy

转载 作者:太空宇宙 更新时间:2023-11-03 20:57:12 25 4
gpt4 key购买 nike

我正在尝试提出一个有效的解决方案,以便能够查询实体列表并正确排序。我在 SQL DB 模式中创建了一个单链表类型结构。我使用 GUID 作为我的 ID,但为了简单起见,我将在此处使用 int。我可以通过在数据库上有一个 SortOrder 列轻松解决这个问题,但由于其他要求,这就是我必须实现此表的方式。

我有一个类似于以下实体模型的表结构:

public class Record
{
public int ID;
public string Name;
public int? ChildID; //References the next record
}

我最初的想法是创建一个如下所示的分部类:

public partial class Record
{
public int SortOrder
{
get
{
//query table and loop through the entire list building it from
//the bottom and keeping count of the integer sort order and return
//the one specific to this record
}
}
}

但是,每次都必须查询整个列表并遍历以找到 SortOrder,这似乎非常低效。还有什么我可以利用的,比如自定义 OrderBy 函数或其他什么?我正在尝试按迭代构建列表时创建的顺序进行排序。例如,ChildID = null 的记录是列表中的最后一个,因为它没有 child 。我将从该记录开始,然后获取它上面的下一个引用前一个作为其 ChildID 的记录,直到列表中没有更多引用 ID 的记录,这应该是在列表完成并正确排序时.没有两条记录具有相同的 ChildID。

如果我在列表中有以下 3 条记录,

ID = 3,  Name = "Apple",  ChildID = 6,
ID = 54, Name = "Orange", ChildID = 3,
ID = 6, Name = "Banana", ChildID = null

然后我希望按顺序得到 Orange、Apple、Banana。

最佳答案

实现此目的的一种方法是编写一个方法,该方法将按排序顺序返回一个列表。你会先找到ChildId == null的记录,将其添加到结果列表,然后继续搜索item.ChildId == previousItem.Id的项目,然后将它们插入列表的开头:

private static IEnumerable<Record> OrderRecords(IReadOnlyCollection<Record> records)
{
// "Exit fast" checks
if (records == null) return null;
if (records.Count < 2) return records.ToList();

// Get last record and add it to our results
Record currentRecord = records.Single(r => r.ChildID == null);
var results = new List<Record> {currentRecord};

// Keep getting the parent reference to the previous record
// and insert it at the beginning of the results list
while ((currentRecord = records.SingleOrDefault(r =>
r.ChildID == currentRecord.ID)) != null)
{
results.Insert(0, currentRecord);
}

return results;
}

在使用中,这看起来像:

private static void Main()
{
var records = new List<Record>
{
new Record {ID = 3, Name = "Apple", ChildID = 6},
new Record {ID = 54, Name = "Orange", ChildID = 3},
new Record {ID = 6, Name = "Banana", ChildID = null}
};

var sortedRecords = OrderRecords(records);

Console.WriteLine(string.Join(", ", sortedRecords.Select(r => r.Name)));

Console.Write("\nPress any key to exit...");
Console.ReadKey();
}

输出

enter image description here

关于c# - 使用单链接实体列表的 Linq 中的自定义 OrderBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49288265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com