The context is that I have one cached set of values in memory that were expensive to fetch, and another set of associated data that is inexpensive to fetch and can’t be cached (business rule). I’ve got it all working but I was just wondering if anyone could think of a less expensive way of doing this sort of update…
foreach (var nonCachedItem in searchItemsNonCached)
{
foreach (var cachedItem in searchItemsCached)
{
if (cachedItem.ID == nonCachedItem.ID)
nonCachedItem.Description = cachedItem.Description;
}
}
it’s basically just to match up the cached information with the information I just got. It all works and the load is almost negligable but I’m kind of a sucker for efficiency.
EDIT: in the above, searchItemsNonCached and searchItemsCached are both Lists of SearchItem where Searchitem is a bespoke object.
Load a
Dictionarywith the cached items and then cycle through each non-cached item looking for a match in the dictionary. This isO(n)as opposed to the nested loop which isO(n^2).If you could consider using a
Dictionaryfor the cached items from the beginning (instead of aList) then you could avoid the step of loading it before finding matches.