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."
Select
. it basically does nothing in your code. it is like if your wroteworkStations.Equals(x.Id)
– Bizhan