Search code examples
linqc#-4.0genericsvargeneric-collections

how to convert var to dictionary and access var using foreach loop


i have a dictionary defined as follows:

Dictionary<string, int> Controls = new Dictionary<string, int>();

using the following code i am putting keys which have similar value into var

var result = (from p in Controls
                         group p by p.Value into g
                         where g.Count() > 1
                         select g);

But neither i am able to convert 'result' into dictionary again or nor i am able to access item inside 'result'

i tried this code but

foreach (System.Linq.Lookup<int, KeyValuePair<string, int>> Item in result)
{

}

Plz help.


Solution

  • try this:

    var dict = result.ToDictionary(x => x.Key, x => x.Select(y => y.Key).ToList())
    

    and access it like

    foreach(var item in dict)
    

    BTW, there's no type var. It's just instruction for the compiler to determine type for variable, but it's strongly typed. In your case, I think, it would be IEnumerable<IGrouping<TKey, TSource>>. Actually you can access result like this too:

    foreach(var item in result)
    {
        // item is type  Lookup<int, KeyValuePair<string, int>>.Grouping
        //  you can go through item like
        foreach(var i in item)
        {
    
        }
    
        // or convert it ToList()
        var l = item.ToList()
        // l is type List<KeyValuePair<string, int>>
    }