Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#字典获取最小值的键_C#_Linq_Dictionary - Fatal编程技术网

c#字典获取最小值的键

c#字典获取最小值的键,c#,linq,dictionary,C#,Linq,Dictionary,今天对你们来说可能是一个简单的问题,但我现在正在兜圈子。考虑这种情况: var tempDictionary = new Dictionary<string, int>(); tempDictionary.Add("user 1", 5); tempDictionary.Add("user 2", 3); tempDictionary.Add("user 3", 5); Console.WriteLine(tempDictionary.Min(x => x.Key) + "

今天对你们来说可能是一个简单的问题,但我现在正在兜圈子。考虑这种情况:

var tempDictionary = new Dictionary<string, int>();
tempDictionary.Add("user 1", 5);
tempDictionary.Add("user 2", 3);
tempDictionary.Add("user 3", 5);

Console.WriteLine(tempDictionary.Min(x => x.Key) + " => " tempDictionary.Min(x => x.Value);
var tempDictionary=newdictionary();
添加(“用户1”,5);
添加(“用户2”,3);
添加(“用户3”,5);
WriteLine(tempDictionary.Min(x=>x.Key)+“=>”tempDictionary.Min(x=>x.Value);
上面返回“用户1=>3”

如何返回字典中具有最低值的键?我所追求的输出应该是这样的:“user2=>3”

有什么想法吗

var keyAndValue = tempDictionary.OrderBy(kvp => kvp.Value).First();
Console.WriteLine("{0} => {1}", keyAndValue.Key, keyAndValue.Value);

如果您的数据集在大小上不平凡,您可以考虑在.S/.P>>P>上使用MIBION扩展。 或

var min=tempDictionary.Aggregate((l,r)=>l.Value

试试这个:
var val=tempDictionary.OrderBy(k=>k.Value).FirstOrDefault();

Console.WriteLine(val.Key+“=>”+val.Value);

排序效率较低,因为它需要O(n log n),但选择最小值应仅为O(n)

我认为这是一个更简单的方法:

tempDictionary.Where(e => e.Value == tempDictionary.Min(e2 => e2.Value)).First()

如果只删除
,你甚至可以得到所有的最小值。First()

我有一个类似的问题,我不喜欢对字典的值进行排序,只需通过一次迭代(排序为>O(N)),就可以找到最小值。你可能需要防止死角和类似情况

    var s = String.Empty;
    var min = Int32.MaxValue;
    foreach (var item in tempDictionary) {
        if (item.Value < min){
            s = item.Key;
            min = item.Value;
        }
    }

    Console.WriteLine(s + " => " + min);
var s=String.Empty;
var min=Int32.MaxValue;
foreach(tempDictionary中的变量项){
如果(项目值<最小值){
s=项。键;
最小值=项目值;
}
}
控制台写入线(s+“=>”+min);

可能的重复(以及对答案的编辑以反映这一点)非常好,这正是我在常规linq中所追求的。只是等待stackoverflow,以便我可以将其标记为我正在寻找的答案。谢谢:)谢谢spender,谢天谢地,列表的大小将非常小,但是moreLinq看起来是一个很有用的工具。谢谢你提醒我:)我认为使用
first
在第一行爆炸可能更安全,而不是将
val
设置为
null
。否则,在调用
Console.WriteLine
之前,应进行
null
检查。
tempDictionary.Where(e => e.Value == tempDictionary.Min(e2 => e2.Value)).First()
    var s = String.Empty;
    var min = Int32.MaxValue;
    foreach (var item in tempDictionary) {
        if (item.Value < min){
            s = item.Key;
            min = item.Value;
        }
    }

    Console.WriteLine(s + " => " + min);