我有一個很大的未排序的項目列表。有些項目很重要,需要先列出,然後是不重要的項目。這些項目應按照兩組的名稱進行排序。我有一個解決方案,但我相信它可以進行優化。首先,它得到一個重要項目清單。然後列出其他所有內容,然後連接結果。有關如何優化這個的任何建議?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();
這裏是正確的輸出:
立即想到important1
important2
not important1
not important2
not important3
not important4
你想如何優化它?爲了執行速度? – 2010-08-06 18:01:06
是的,可以用較少的代碼來完成,但我對性能感興趣。 – soconnor 2010-08-06 18:02:07
現在跑得太慢了嗎?或者你是否試圖解決尚未發生的問題? – 2010-08-06 18:02:48