How much less efficent would the linq technique be in the following case and could either be optimised?
Linq technique:
public String FindProviderName(Int32? TrueName)
{
String providerName = (from p in this.Providers
where p.TrueName == TrueName
select p.ProviderName).First().ToString();
return providerName;
}
Walking technique:
public String FindProviderName(Int32? TrueName)
{
String providerName = String.Empty;
foreach (IProvider provider in this.Providers)
{
if (provider.TrueName == TrueName)
{
providerName = provider.ProviderName;
break;
}
}
return providerName;
}
If that is LINQ-to-objects, they’ll both be pretty fast. If you want faster, consider a
Dictionary<int,string>and useTryGetValue(...). Obviously you need to pre-generate the dictionary, perhaps via ToDictionary().Note that the two examples shown are different when there is no match; one throws; one returns an empty string. Also, there is no need to call ToString() on a string.
Re the faster version (comments); you need a field,
And at some point prior to use (or after data changes) you need to populate it:
Then your lookup would be like: