Home > front end >  C# - Partial Search in Hashtables
C# - Partial Search in Hashtables

Time:12-22

Can we check for a part of string in hashtable key? For example, our key is

key = cardnumber  ","  tokennumber

Eg, key would be then

key = 1234,7463

I know have a function called containskey() but do we have something that could partially check for a string in a hashtable key?

For example, if we could search

if(key.contains(tokennumber))
{
//do something
}

CodePudding user response:

You can do it but the lookup won't be as fast.

You can cast the Keys Collection to of type string and then perform basic Linq on it to get the Keys that you want.

Example:

var listOfKeys = hashTable.Keys.Cast<string>().Where(x => x.Contains(tokennumber)).ToList();

after this, you can loop over the Keys and perform the operation that you want.

CodePudding user response:

That's a bad idea: you waste an advantage of Hashtables (btw, don't use class Hashtable, use Dictionary<TKey, TValue> instead) and key lookup complexity becomes O(n) vs O(1) in nomral key retrieving.

If your tokens are unique, consider incapsulating your key data in some class and provide IEqulityComparer to dictionary. For example:

public class KeyData
{ 
    public string CardNumber { get; set; }

    public string TokenNumber { get; set; }

    public override string ToString() => $"{CardNumber},{TokenNumber}";
}

public class KeyDataTokenComparer : IEqualityComparer<KeyData>
{
    public bool Equals(KeyData x, KeyData y) => x?.TokenNumber == y?.TokenNumber;

    public int GetHashCode([DisallowNull] KeyData obj) => obj.TokenNumber.GetHashCode();
}

// usage:
var dict = new Dictionary<KeyData, SomeClass>(new KeyDataTokenComparer());
// filling dict
if (dict.ContainsKey(new() { TokenNumber = "token_to_search" }))
{ }

Another approach (especially if your tokens aren't unique and/or if you need to fast lookup card number after a token number) – to use composite dictionary class. For example:

var dict = new Dictionary<string, Dictionary<string, SomeClass>>();

The key here is your token number, value – a dictionary where the key is card number and the value - is your original value.

  • Related