2012-03-07 73 views
0

我有一本字典,像这样 -其中有从字典<INT,列表<int>>与lambda表达式最高值算出特定键

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] 

现在我想找到列表中具有最高值的关键字。

喜欢在这种情况下,拉姆达应返回3其表示键 - 值对,其中关键是因为3数字7是存在于在键恰好是3字典中的列表。

回答

3

它有点哈克,但应该工作。

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; 
+0

你能解释在lambda新的关键字。我没有得到那部分。 – 2012-03-08 12:49:59

+0

在这种情况下,new会生成一个具有两个属性Key和Value的匿名类型。看到这个问题的详细答案。 http://stackoverflow.com/questions/48668/how-should-anonymous-types-be-used-in-c – Alex 2012-03-08 12:52:04

+0

还有一个问题,如果我想在列表中找到最少的数字,那么max是当下。 – 2012-03-08 12:55:33

1

不幸的是,LINQ to Objects中没有内置任何内容,这使得这特别令人愉快。您可以使用MaxBy从我MoreLINQ项目虽然与需要的轻微把戏每个列表上使用Max还有:

var maxKey = pegMap.MaxBy(x => x.Value.Max()) 
        .Key; 

注意,如果存在具有相同的顶级元素列表中的多个按键,它将返回第一个。

1

这应该工作,

pegMap.SelectMany(a => a.Value, (a, b) => new {holdKey = a.Key,listValue= b}).OrderByDescending(a=>a.listValue).First().holdKey; 
+0

:(,抱歉与@Alex的回答几乎相同。在回答之前没有刷新 – labroo 2012-03-07 07:11:02

+0

这不是问题,我认为这是[所以]应该考虑的问题。包括我在内的很多人在回答或评论之前都不刷新。一个实时问题。 – 2012-03-08 12:51:21

相关问题