Search code examples
c#listdictionarycasting

Find dictionary matches from list of base class


I have a quite odd question. I am working on a big project and i am implementing a core feature after millions of lines of code. I am not allowed to alter some parts of the code and it seems like i have to try this way.

I have two classes as A and B. A is derived from B.

public class B{}
public class A : B{}

I have a SortedList<string, A>, i need to cast the SortedList into List<B>. Operate on List<B> then cast the list into SortedList again.

For example:

SortedList<string, B> items;
public List<A> GetItems()
{
   return items.Values.Cast<B>().ToList(); //Getting values works
}

public void SetItems(List<B> newItems)
{
    items = CastWithMagic(newItems); //How to make casting work?
}

There are 2 possible changes on A items.

  • Changes on B(base class variables)
  • Removed items from the list.

I want to apply changes on List<B> to SortedList<string, A>


Solution

  • There are 2 possible changes on A items.

    • Changes on B(base class variables)
    • Removed items from the list.

    Changes to the objects will be reflected in both lists, since the lists just contain references to the same objects. So all you should need to handle is objects that are deleted from the List. I believe you'll have to loop through the sorted list to see if the objects have been removed from the list:

    public void SetItems(List<B> newItems)
    {
        foreach(string key in items.Keys)
        {
            if(!newItems.Contains(items[key] as B))
                items.Remove(key);
        }
    }
    

    Note that this is inefficient since you're looping through both collections, making it O(m*n) - if your collections are small and performance is not critical then you may be OK, but start with this and find ways to make it more efficient (maybe removing from the source collection instead of the copied list?)