gpt4 book ai didi

c# - 查找值小于搜索值的最大 Dictionary

转载 作者:太空狗 更新时间:2023-10-29 21:08:38 26 4
gpt4 key购买 nike

我有Dictionary<int,string>使用像这样的升序键:

var myDictionary = new Dictionary<int,string>
{
{750,"one"},
{1500,"two"},
{2500,"three"},
{5000,"four"},
{10000,"five"},
{25000,"six"}
}

我有var myValue = 3000.52

我需要找到最大的 myDictionary比我的值(value)小的 key 。在这种情况下,我需要返回 2500。

我试过:

foreach (var key in myDictionary.Keys.Where(key => key <= myValue))
{

}

但是,如您所料,所有较小的值也匹配。

如何找到小于我的搜索值的最大键?

最佳答案

使用LinQ是我认为最简单的方式:

int myKey = myDictionary.Where(x => x.Key < myValue)
.OrderByDescending(x => x.Key)
.First().Key;

关于c# - 查找值小于搜索值的最大 Dictionary<int,string> 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26564329/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com