LINQ: Get all objects with a matching string property from an incoming IEnumerable<string> in a performant way

1122 views c#
4

I just saw this piece of code and asked myself how it can be improved to reduce the amount of queries. Tried a few LINQ statements but could not find an answer.

    public static Dictionary<string, Computer> GetComputer(IEnumerable<string> workStations)
    {
        var dict = new Dictionary<string, Computer>();
        using (var db = new ComputerContext())
        {
                foreach (var workStation in workStations)
                {
                    var t = db.Computers.FirstOrDefault(o => o.Id.Equals(workStation));

                    if (!dict.ContainsKey(workStation))
                    {
                        dict.Add(workStation, t);
                    }
                }

                return dict;
        }
    }

When trying someting like this:

var computers = db.Computers.Where(x => workStations.Select(y => y).Equals(x.Id)).ToList();

foreach (var computer in computers)
{
    if (!dict.ContainsKey(computer.Id))
    {
        dict.Add(computer.Id, computer);
    }
}

Intellisense is telling me "Suspicious comparison: there is no type in the solution which is inherited from both

'System.Collections.Generic.IEnumerable' and 'string'" which leds to an Exception "Cannot compare elements of type 'System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only primitive types, enumeration types and entity types are supported."

answered question

Id is just an example (it's a string in this example)

Yes, I got that. the problem is with the usage of Select. it basically does nothing in your code. it is like if your wrote workStations.Equals(x.Id)

1 Answer

13

The problem is in your query. Try this code:

var computers = db.Computers.Where(x => workStations.Any(y => y.Equals(x.Id)).ToList();

foreach (var computer in computers)
{
    if (!dict.ContainsKey(computer.Id))
    {
        dict.Add(computer.Id, computer);
    }
}

posted this

Have an answer?

JD

Please login first before posting an answer.