转换一个IOrderedEnumerable< KeyValuePair<字符串,整数>>成字典<字符串,整数> [英] Convert an IOrderedEnumerable<KeyValuePair<string, int>> into a Dictionary<string, int>

查看:576
本文介绍了转换一个IOrderedEnumerable< KeyValuePair<字符串,整数>>成字典<字符串,整数>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是继回答另一个问题,和我:

  // itemCounter是一个字典<字符串,整数>和我只是想保持
//键/与顶级maxAllowed值对值
如果(itemCounter.Count> maxAllowed){
IEnumerable的< KeyValuePair<字符串,整数>> sortedDict = $ B从itemCounter排序依据entry.Value降选择中入口$ B;
sortedDict = sortedDict.Take(maxAllowed);
itemCounter = sortedDict.ToDictionary<字符串,整数>(/ *我该怎么办这里* /?);
}



Visual Studio的要求参数 Func键<字符串, INT>的KeySelectors 。我尝试以下几个半相关的例子,我在网上找到,放在 K => k.Key ,但给出了一个编译器错误:




'System.Collections中.Generic.IEnumerable< System.Collections.Generic.KeyValuePair<字符串,整数>>
不包含定义'ToDictionary和最好的
扩展方法重载
'System.Linq.Enumerable.ToDictionary< TSource,TKEY的>(System.Collections.Generic.IEnumerable< TSource>中
System.Func< TSource,TKEY的>)
有一些无效参数



解决方案

您指定不正确的通用参数。你是说TSource是字符串,而实际上它是一个KeyValuePair



这是正确的:

  sortedDict.ToDictionary< KeyValuePair<字符串,整数>中字符串,整数>(对= GT; pair.Key,对= GT; pair.Value); 



与短版之中:

  sortedDict.ToDictionary(双= GT; pair.Key,对= GT; pair.Value); 


I was following the answer to another question, and I got:

// itemCounter is a Dictionary<string, int>, and I only want to keep
// key/value pairs with the top maxAllowed values
if (itemCounter.Count > maxAllowed) {
    IEnumerable<KeyValuePair<string, int>> sortedDict =
        from entry in itemCounter orderby entry.Value descending select entry;
    sortedDict = sortedDict.Take(maxAllowed);
    itemCounter = sortedDict.ToDictionary<string, int>(/* what do I do here? */);
}

Visual Studio's asking for a parameter Func<string, int> keySelector. I tried following a few semi-relevant examples I've found online and put in k => k.Key, but that gives a compiler error:

'System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string,int>>' does not contain a definition for 'ToDictionary' and the best extension method overload 'System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>)' has some invalid arguments

解决方案

You are specifying incorrect generic arguments. You are saying that TSource is string, when in reality it is a KeyValuePair.

This one is correct:

sortedDict.ToDictionary<KeyValuePair<string, int>, string, int>(pair => pair.Key, pair => pair.Value);

with short version being:

sortedDict.ToDictionary(pair => pair.Key, pair => pair.Value);

这篇关于转换一个IOrderedEnumerable&LT; KeyValuePair&LT;字符串,整数&GT;&GT;成字典&LT;字符串,整数&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆