【问题标题】:how to convert var to dictionary and access var using foreach loop如何将 var 转换为字典并使用 foreach 循环访问 var
【发布时间】:2013-09-26 14:35:43
【问题描述】:

我有一个定义如下的字典:

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

使用以下代码,我将具有相似值的键放入 var

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

但我既不能再次将“结果”转换为字典,也不能访问“结果”内的项目

我试过这段代码,但是

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

}

请帮忙。

【问题讨论】:

    标签: linq c#-4.0 generics var generic-collections


    【解决方案1】:

    试试这个:

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

    并像访问它一样

    foreach(var item in dict)
    

    顺便说一句,没有类型 var。编译器确定变量的类型只是instruction,但它是强类型的。在你的情况下,我认为应该是IEnumerable&lt;IGrouping&lt;TKey, TSource&gt;&gt;。其实你也可以像这样访问result

    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>>
    }
    

    【讨论】:

    • 感谢您的回复,它对我有用。如果你能帮忙,还有一件事。如何使用'foreach'循环访问'tempdic' Dictionary> tempdic = result.ToDictionary(x => x.Key, x => x.Select(y => y.Key).ToList( ));
    猜你喜欢
    • 2013-06-07
    • 2017-07-04
    • 2021-12-25
    • 1970-01-01
    • 2022-10-23
    • 2021-03-01
    • 2013-02-27
    • 1970-01-01
    • 2016-07-20
    相关资源
    最近更新 更多