Search code examples
c#keysorteddictionary

C# - How to find all items in SortedDictionary which have similar keys?


I have a SortedDictionary:

static SortedDictionary<string, int> myDictionary = new SortedDictionary<string, int>();

where the keys represent strings something like that:

string key = someNumber + " " + row + " " + col + " " + someString;

What I want is to find all the items in the sorted dictionary that have specific row and col. For example if I have the following keys:

1 2 3 p 
3 2 3 p 
2 2 3 t 
5 1 6 p 
8 2 1 p 
7 2 3 t

I want to get only these keys that have row=2 and col=3:

1 2 3 p 
3 2 3 p 
2 2 3 t 
7 2 3 t

Solution

  • Unfortunately in this case you need to iterate over the whole collection and select the items that match your criteria (so not much use of the dictionary itself):

    public IList<int> FindValues(int row, int col)
    {
        myDictionary
            .Where(item => MatchKey(item.Key, row, col))
            .Select(item => item.Value)
            .ToList();
    }
    
    public bool MatchKey(string key, int row, int col)
    {
        var splitKey = key.Split();
        return splitKey[1] == row.ToString() && splitKey[2] == col.ToString();
        // or match the key according to your logic
    }
    

    Though if you need to query by row and column often, then it's better to build a different data structure first. Maybe

    Dictionary<Coord, IList<int>> myDict;
    

    Where Coord is a class/struct (and overrides Equals, GetHashCode)

    class Coord
    {
        public int Row { get; set; }
        public int Column { get; set; }
    }