There and That
There and That

Reputation: 165

C# Iterating over a dictionary passed as a generic

I am having trouble trying to iterate over a dictionary passed to a function as a generic. For example, I have a function that loads data from a DB.

public T Load<T>(...)

This function can be called like so, with which I have no problems;

someclasstype data = Load<someclasstype>(...);

List<someclasstype> data = Load<List<someclasstype>>(...);

I've recently tried to extend this to be able to deal with dictionaries as well, and calling it like so:

Dictionary<long, someclasstype> data = Load<Dictionary<long, someclasstype>>(...)

I can load the data without a problem and store it in the dictionary no problem.

At this stage, the dictionary, with all its keyvaluepairs is stored in a variable called result, and I'm creating an IEnumerable with

IEnumerator resultIdx = ((IEnumerable)result).GetEnumerator();
if (!resultIdx.MoveNext())
    return (T)result;

object kvp = resultIdx.Current;

So far so good. I can see the value of the key and the value of the value in a watch, or by mouseover on the kvp variable.

But I cannot figure out how to get the value part of the keyvaluepair from kvp.

// None of these work - I get compile time errors, unboxing errors, or invalid cast errors.
object item = ((KeyValuePair<TKey, TValue>)kvp).Value;

object item = ((KeyValuePair<long, object>)kvp).Value;

object item = ((T)kvp).Value // Never had a hope for this, but desperation...

Does anyone have any idea how I can do this?

Upvotes: 3

Views: 192

Answers (3)

Ashley John
Ashley John

Reputation: 2453

try adding dynamic kvp = resultIdx.Current; . Then you can use kvp.Value

Upvotes: 2

There and That
There and That

Reputation: 165

Answer provided by Dede in comments:

"Use Reflection ?

object key kvp.GetType().GetProperty("Key").GetValue(kvp); 
object value kvp.GetType().GetProperty("Value").GetValue(kvp); 

Not very optimized, but can work... – Dede 24"

Upvotes: 0

Pouya Abadi
Pouya Abadi

Reputation: 255

You can rewrite the function into two functions like.

public T Load<T>(...)
//Or maybe public List<T> Load<T>(...)

and

public Dictionary<long, T> LoadD<T>(...)

Then you can cast result to KeyValuePair<long, T> in LoadD. You can call Load from LoadD to minimize code rewriting.

Upvotes: 1

Related Questions