Compare and update two lists in C #

The context is that I have one cached set of values ​​in memory that were expensive to extract and another set of related data that are inexpensive to extract and cannot be cached (business rule). Everything works for me, but I'm just wondering if anyone could think of a less expensive way to do such an update ...

foreach (var nonCachedItem in searchItemsNonCached) { foreach (var cachedItem in searchItemsCached) { if (cachedItem.ID == nonCachedItem.ID) nonCachedItem.Description = cachedItem.Description; } } 

this is basically just for matching the cached information with the information I just received. It all works and the load is almost careless, but I'm kind of useful for efficiency.

EDIT: in the above example, searchItemsNonCached and searchItemsCached are both SearchItem lists, where Searchitem is a custom object.

+4
source share
4 answers

Download a Dictionary with cached items, and then go through each item without caching that looks for a match in the dictionary. This is O(n) in contrast to the nested loop, which is equal to O(n^2) .

 var cachedDictionary = new Dictionary<int, YourType>(); foreach (var item in searchItemsCached) { cachedDictionary.Add(item.ID, item); } foreach (var item in searchItemsNonCached) { YourType match; if (cachedDictionary.TryGetValue(out match)) { item.Description = match.Description; } } 

If you could use Dictionary for cached items from the very beginning (instead of List ), you could avoid loading it until you find matches.

+2
source

Store your cache files in a dictionary. Now you can update only if the key exists.

+5
source

What you are trying to do is essentially a connection (in the sense of a database), in particular, equi-join. You can check out this section of the Wikipedia article on union algorithms. The code you mentioned above is a union of nested loops, and the adymitruk clause is a hash join, but as Lou Franco noted, the best approach probably depends on what order or structure (if any) in your collections.

If searchItemCached is just an unordered list, then a hash join is probably your best bet - just create a dictionary from one collection or another with an identifier as a key, then scroll through another collection by looking at the corresponding items from the dictionary. If searchItemCached already has a dictionary with a key by identifier, then a hash join is by far the best choice. If searchItemCached and searchItemsNonCached are sorted by identifier, then sort-merge join is possible.

0
source

Another approach is that you can write a linq expression and join two identifier lists and create new objects of the same type with updated values.

ex

 from nc in searchItemsNonCached join c in searchItemCached on nc.ID equals c.ID select new (same type) // and assign the desc from c.Description 
-1
source

All Articles