![](/img/trans.png)
[英]Create an int[] from Dictionary<int, List<int>>, from each dictionary element's Value List<int> I need an array which contains all dictionary elements
[英]Finding specific key which has highest value from Dictionary<int, List<int>> with lambda expression
我有一本这样的字典——
public static Dictionary<int, List<int>> pegMap = new Dictionary<int, List<int>>();
现在我已经填充了字典,比如 -
Key: 1 => Value: [3,2]
Key: 2 => Value: []
Key: 3 => Value: [6,7]
现在我想找到列表中具有最高值的键。
就像在这种情况下,lambda 应该返回3
,它表示 key 为3
的键值对,因为数字 7 出现在字典中的列表中,而 key 恰好是3
。
它有点hacky,但应该可以工作。
var dict = new Dictionary<int, List<int>>();
dict.Add(1, new List<int>() { 1, 2 });
dict.Add(2, new List<int>() { 4, 5 });
dict.Add(3, new List<int>() { 1, 7 });
var max = dict.Select(x => new { Key = x.Key, Value = x.Value.Max() }).OrderByDescending(x => x.Value).First().Key;
// returns 3
// Other sample input
dict.Add(1, new List<int>() { 1, 2 });
dict.Add(2, new List<int>() { 4, 7 });
dict.Add(3, new List<int>() { 1, 2 });
// returns 2
dict.Add(1, new List<int>() { 1, 2 });
dict.Add(2, new List<int>() { 4, 7 });
dict.Add(3, new List<int>() { 1, 7 });
// returns 2
dict.Add(1, new List<int>() { 1,10 });
dict.Add(2, new List<int>() { 4, 7 });
dict.Add(3, new List<int>() { 1, 7 });
// returns 1
编辑:到列表中具有最大值的最小值:
var min_value_in_maxList = dict.Select(x => new { Key = x.Key, ValueMax = x.Value.Max(), ValueMin = x.Value.Min() }).OrderByDescending(x => x.ValueMax).First().ValueMin;
这应该有效,
pegMap.SelectMany(a => a.Value, (a, b) => new {holdKey = a.Key,listValue= b}).OrderByDescending(a=>a.listValue).First().holdKey;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.