我有一个未排序的大型项目列表。其中一些项目很重要,需要首先列出,然后是不重要的项目。这些项目应按名称在两个组中排序。我有一个解决方案,但我认为它可以优化。首先,它获取重要项目列表。然后获取其他所有内容的列表,然后连接结果。有什么建议可以优化吗?
以下是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