LINQ query optimization?

I have a large unsorted list of items. Some points are important and should be listed first, followed by non-essential elements. Items must be sorted by name in two groups. I have a solution, but I believe that it can be optimized. First, he gets a list of important items. Then a list of everything else, then combines the results. Any suggestions for optimizing this?

Here is a simplified version of the problem for 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();

Here's the correct conclusion:

important1
important2
not important1
not important2
not important3
not important4
+3
source share
2 answers

One approach that immediately comes to mind is to use OrderBy as well as ThenBy to avoid repeatedly querying the original data source. Sort of:

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

, - , OrderBy . , , .

+5
var prioritized = 
        from item in items 
        select new {
        Importance = importantItemIDs.Contains((string) item.Attribute)? 1 :2,
        Item = item
        };

var fullList =   from pitem in prioritized 
                 orderby pitem.Importance, pitem.Item.Value
                 select pitem.Item.Value;
+1

Source: https://habr.com/ru/post/1758440/


All Articles