I have the following code in one of my methods:
foreach (var s in vars) { foreach (var type in statusList) { if (type.Id == s) { Add(new NameValuePair(type.Id, type.Text)); break; } } }
This seems sort of ineffective to me, and I was wondering if there was a way to substitute at least one of the foreaches wih a LINQ query. Any suggestions?
EDIT: vars is an array of strings and the Add method adds an item to a CSLA NameValueList.
EDIT: I hadn’t noticed the
break;beforeIf there could be more than one type with the relevant ID, then you need to use
FirstOrDefaultas per Keith’s answer or my second code sample below.EDIT: Removing ‘multi-from’ version as it’s unnecessarily inefficient assuming equality/hashcode works for whatever the type of
type.Idis.A join is probably more appropriate though:
You might want to make an
AddRangemethod which takes anIEnumerable<NameValuePair>at which point you could just callAddRange(query).Alternatively, you can use a LookUp. This version makes sure it only adds one type per ‘s’.
The benefit of this is that it only goes through the list of types once to build up a dictionary, basically.