LINQ查询优化?

soc*_*nor 3 linq

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

以下是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();
Run Code Online (Sandbox Code Playgroud)

这是正确的输出:

important1
important2
not important1
not important2
not important3
not important4
Run Code Online (Sandbox Code Playgroud)

Rya*_*ner 5

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

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

我不确定那里是否需要三元运算符 - 我忘记了OrderBy如何处理布尔结果.无论如何,这不应该是一个主要的性能问题,并且可能更清楚一点.