【问题标题】:Linq return WhereEnumerableIterator from Dictionary value matches?Linq从Dictionary值匹配返回WhereEnumerableIterator?
【发布时间】:2013-06-24 15:33:09
【问题描述】:

我有以下代码从Dictionary<int, string> buttonGroups返回项目 其中值与某个字符串匹配。

    public static void RemoveColorRange(List<Button> buttons, int[] matches)
    {
        Dictionary<int, string> buttonGroups = new Dictionary<int, string>();

        foreach (Button btn in buttons)
        {                               
            if ((int)btn.Tag == matches[0] || (int)btn.Tag == matches[1])
                continue;

            SolidColorBrush brush = (SolidColorBrush)btn.Background;
            Color color = new Color();
            color = brush.Color;
            buttonGroups.Add((int)btn.Tag, closestColor(color));               
        }

        var buttonMatches = buttonGroups.Where(x => x.Value == 'somestring');
    }

但是它返回以下类型而不是字典对象。我似乎无法从 buttonMatches 中检索任何值。我错过了什么?

{System.Linq.Enumerable.WhereEnumerableIterator<System.Collections.Generic.KeyValuePair<int,string>>}

【问题讨论】:

    标签: c# linq dictionary


    【解决方案1】:

    那是因为Where 不返回字典。要拥有一本字典,您需要将过滤结果显式转换为一个:

    var buttonMatches = buttonGroups.Where(x => x.Value == 'somestring')
                                    .ToDictionary(x => x.Key, x => x.Value);
    

    【讨论】:

    • 或者您应该在添加到字典之前进行检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多