Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ operations on IDictionary

Let's suppose I have the following dictionaries:

private Dictionary<int, string> dic1 = new Dictionary<int, string>()
{
      { 1, "a" },
      { 2, "b" },
      { 3, "c" }
}

private Dictionary<SomeEnum, bool> dic2 = new Dictionary<SomeEnum, bool>()
{
      { SomeEnum.First, true },
      { SomeEnum.Second, false },
      { SomeEnum.Third, false }
}

I want to convert these two dictionaries into a Dictionary<string, object>

For example:

 dic1 = new Dictionary<string, object>()
 {
     { "1", "a" },
     { "2", "b" },
     { "3", "c" }
 }

 dic2 = new Dictionary<string, object>()
 {
     { "First", true },
     { "Second", false },
     { "Third", false }
 }

As you can see, the string key of these dictionaries is just the string representation of the previous ones.

The method that is responsible for the conversion has the following signature:

 public static object MapToValidType(Type type, object value)
 {
     //....

     if(typeof(IDictionary).IsAssignableFrom(type))
     {
         //I have to return a Dictionary<string, object> here
         return ??;
     }
 }

I have tried the following:

 ((IDictionary)value).Cast<object>().ToDictionary(i => ...);

But i was casted to an object, so I cannot access the key or value items. For that I would need to cast it to the appropiate KeyValuePair<TKey, TValue>, but I don't know TKey or TValue type.

Another solution is to do this:

IDictionary dic = (IDictionary)value;
IList<string> keys = dic.Keys.Cast<object>().Select(k => Convert.ToString(k)).ToList();
IList<object> values = dic.Values.Cast<object>().ToList();
Dictionary<string, object> newDic = new Dictionary<string, object>();
for(int i = 0; i < keys.Count; i++)
   newDic.Add(keys[0], values[0]);
return newDic;

However, I'm not much of a fan of this approach and I am really looking for a simpler and friendlier one line LINQ statement.

like image 218
Matias Cicero Avatar asked Jul 10 '15 16:07

Matias Cicero


People also ask

Can use Linq for dictionary?

In LINQ, ToDictionary() Method is used to convert the items of list/collection(IEnumerable<T>) to new dictionary object (Dictionary<TKey,TValue>) and it will optimize the list/collection items by required values only.

How do you add to a dictionary in C#?

Add() Method is used to add a specified key and value to the dictionary. Syntax: public void Add (TKey key, TValue value);

What is ToDictionary?

The ToDictionary method is an extension method in C# and converts a collection into Dictionary. Firstly, create a string array − string[] str = new string[] {"Car", "Bus", "Bicycle"}; Now, use the Dictionary method to convert a collection to Dictionary − str.ToDictionary(item => item, item => true);

What is Linq in C# with example?

LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve data from different sources and formats. It is integrated in C# or VB, thereby eliminating the mismatch between programming languages and databases, as well as providing a single querying interface for different types of data sources.


1 Answers

You can try this, no LINQ though, i think you don't need:

 Dictionary<string, object> ConvertToDictionary(System.Collections.IDictionary iDic) {
            var dic = new Dictionary<string, object>();
            var enumerator = iDic.GetEnumerator();
            while (enumerator.MoveNext()) {
                dic[enumerator.Key.ToString()] = enumerator.Value;
            }
        return dic;
    }

Or a Linq one:

return iDic.Keys.Cast<object>().ToDictionary(k=> k.ToString(), v=> iDic[v]);
like image 51
George Avatar answered Oct 13 '22 00:10

George