usefulBee usefulBee - 2 months ago 6
C# Question

Most Efficient Way to Get a Single Item Based on Priority Condition

I have a scenario where there are multiple images within each group and a single image needs to be extracted based on a string criteria.

Below is the way it is done right now, and it works; however, not sure if this is the most efficient way, performance, size, and maybe practice wise too

foreach (var g in groups)
{
SomeType file = null;

if (file == null)
{
file = g.Where(i =>
i.URL.Contains("StringA")
).FirstOrDefault();
}
if (file == null)
{
file = g.Where(i =>
i.URL.Contains("StringB")
).FirstOrDefault();
}
if (file == null)
{
file = g.Where(i =>
i.URL.Contains("StringC")
).FirstOrDefault();
}
if (file == null)
{
// etc...
}
if (file == null)
{
file = g.FirstOrDefault();
}
}

Answer

I'm afraid you might find this answer slightly boring but I would avoid trying to find some extremely impressive-looking but complex linq query. I'm sure it could be done but it's not worth the headache.

Just stick all your strings in an array and check them in order of priority. Unless you're running through a large number of items it will be plenty fast enough. You're not executing a db query - your foreach loop makes it clear that your data is already in memory.

So, I'd lose the big if statement and aim for something along the lines of:

string [] my_list = new string [] {"StringA", "StringB", "StringC"};

foreach (var g in groups)
{
    foreach (string s in my_list)
    {
        file = g.Where(i => i.URL.Contains(s)).FirstOrDefault();
        if (file != null)
            break;
    }
    if (file == null)
    {
        file = g.FirstOrDefault();
    }
}

Like I said, not very exciting, but it's dead easy to change your priorities in your search and \ or add and remove strings.

HTH,

Adam.