0

I am looking for a quick way to find if hashtable (string to byte array) collection values contains a given value, i can't use the given contains as it will compare the array object not its values.

i don't mind using linq / extension / implementing contains as long as it is short.

i have tried:

byte[] givenArr = new[]{1,2,3,4}; //(a given arr)
bool contains=false;
Hashtable table;
foreach(var val in table.values)
  if (CompareBytesFunction((byte[])val,givenArr))
      contains=true;

where compare bytes is a function to compare the 2 given byte arrays, i feel this is not the right approach. there might be a simpler way to get this without the helper method.

2
  • 1
    can you show us what u have tried we can't start from a simple description Commented Mar 30, 2014 at 13:17
  • There is no other way than iterating over the byte array looking for your byte(s). Commented Mar 30, 2014 at 13:25

2 Answers 2

2

Even though it's pretty much against the concept of Hashtables which should be searched by key, you can use such code:

//suppose this is the byte array you're looking for:
byte[] b = new byte[] { 1, 3, 5 };

bool exists = myHashtable.Values.OfType<byte[]>().
    ToList().Exists(c => c.SequenceEqual(b));
Sign up to request clarification or add additional context in comments.

15 Comments

why you are calling ToList after Cast and OfType ?
Simpler version : myHashtable.Values.Cast<byte[]>().ToList().Exists(c => c.SequenceEqual(b));
Great, exactly what i needed, also protects me from exception in case table was modified in the process. (my solution will throw exception in such a case)
@Selman22 was able to optimize a bit, but IEnumerable doesn't have the .Exists() method that I originally wanted so I fear one .ToList() is still needed. :(
@josh This solution will also throw an exception if another thread modifies the table.
|
0

You should probably implement an IEqualityComparer that can hash and compare byte[]. Then you can just use the normal hashtable methods.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.