gpt4 book ai didi

LINQ 查询优化?

转载 作者:行者123 更新时间:2023-12-01 11:07:56 25 4
gpt4 key购买 nike

我有一大堆未分类的项目。有些项目很重要,需要先列出,然后是不重要的项目。项目应在两组中按名称排序。我有一个解决方案,但我相信它可以优化。首先,它获得重要项目的列表。然后列出其他所有内容,然后连接结果。关于如何优化它有什么建议吗?

这是 LINQPad 问题的简化版本:

var doc = XDocument.Parse(@"
<items>
<item id='a'>not important4</item>
<item id='b'>important2</item>
<item id='c'>not important2</item>
<item id='d'>not important3</item>
<item id='e'>important1</item>
<item id='f'>not important1</item>
</items>");
// identify which items are important
string[] importantItemIDs = new string[] { "b", "e" };
var items = doc.Root.Elements("item");

// get a list of important items (inner join)
var importantList = from itemID in importantItemIDs
from item in items
orderby (string) item.Value
where itemID == (string) item.Attribute("id")
select item;

// get items that are not important items
var notImportantList = items.Except(importantList).OrderBy(i => (string) i.Value);

// concatenate both sets of results into one list
var fullList = importantList.Concat(notImportantList);
fullList.Select(v => v.Value).Dump();

这是正确的输出:

important1
important2
not important1
not important2
not important3
not important4

最佳答案

立即想到的一种方法是利用 OrderBy 和 ThenBy 来避免多次查询原始数据源。像这样的东西:

var list = items
.OrderBy(i => importantItemIDs.Contains(i.Attribute("id") ? 0 : 1)
.ThenBy(i => i.Value);
.Select(i => i.Value);

我不确定那里是否需要三元运算符 - 我忘记了 OrderBy 如何处理 bool 结果。无论如何都不应该成为主要的性能问题,并且可能更清晰一些。

关于LINQ 查询优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3426434/

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