Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple Linq Where statements

Tags:

c#

asp.net

linq

I've created a function to filter and sort the content of a list.

It's seems a bit 'bitty', however Linq isn't strong point. I'm wondering if the function can be streamlined, either from a performance perspective or even asthetic perspective.

Here's the code:

// Deserialise the XML to create a class of active rows

    var agents = XmlHelper
        .Deserialise<AgentConfigs>("~/Pingtree.xml")
        .Agents
        .Where(x => x.IsActive == true);

// First - get 'direct' agents and order them

    var direct = agents
        .Where(x => x.IsDirect)
        .OrderByDescending(x => x.MinPrice);

// Second - get indirect agents and order them

    var agency = agents
        .Where(x => !x.IsDirect)
        .OrderBy(x => x.Priority);

// Bolt the 2 sublists together, retaining the order

    Agents = direct.Concat(agency).ToList();

Any thoughts on how this could be improved?

like image 891
John Ohara Avatar asked Dec 08 '15 09:12

John Ohara


1 Answers

You could use GroupBy or ToLookup to split both, i prefer ToLookup in this case:

var activeAgentDirectLookup = XmlHelper
    .Deserialise<AgentConfigs>("~/Pingtree.xml")
    .Agents
    .Where(x => x.IsActive == true)
    .ToLookup(a => a.IsDirect);

Agents = activeAgentDirectLookup[true].OrderByDescending(x => x.MinPrice)
    .Concat(activeAgentDirectLookup[false].OrderBy(x => x.Priority))
    .ToList();

A lookup is similar to a dictionary with a bool as key in this case(so two possible groups). The values are IEnumerable<Agents>, so all agents which are either IsDirect or !IsDirect. The benefit here is that you only need to evaluate it once.

like image 71
Tim Schmelter Avatar answered Oct 04 '22 22:10

Tim Schmelter