c# - 查找值在字典中的范围

标签 c# dictionary

我有一些这种形式的数据(字典):

Value0  Text1
Value1  Text2
Value2  Text3
Value3  Text4
Value4  Text5

我现在必须遍历一个可能具有任意随机值的数组。

foreach value in random array
{
    if value is between (value0 && value1)
    console.writeline(Text1)
    if value is between (value1 && value2)
    console.writeline(Text2)
    if value is between (value2 && value3)
    console.writeline(Text3)
    if value is between (value3 && value4)
    console.writeline(Text4)
}

我在这里面临的问题是,对于数组的每个值,我应该能够检测到它的范围(大于值 0 且小于值 1),从而获得相应的文本。但是,字典不是常量,可以有任意数量的值,因此我不能像上面那样使用这些 if 条件。 (例如:字典可能有另一个条目 Value5 Text6)

做这件事的合适方法是什么?

最佳答案

您不能使用 Dictionary<TKey,TValue> 执行此操作,因为它不会保持其中的项目有序。但是你可以使用 SortedDictionary<TKey, TValue> (或 SortedList<TKey, TValue> )来做到这一点:

TValue GetValue<TKey, TValue>(SortedDictionary<TKey, TValue> dictionary, TKey key)
{
    var comparer = dictionary.Comparer;

    TValue result = default(TValue);

    foreach (var kvp in dictionary)
    {
        if (comparer.Compare(key, kvp.Key) < 0)
            return result;

        result = kvp.Value;
    }

    return result;
}

关于c# - 查找值在字典中的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9974724/

相关文章:

c# - 返回复杂类型以使用 AJAX 查看

python - 如何从没有 None 字段的类创建字典?

python - 解析空格分隔的命名字段

python - 有没有更简单的方法来转换这些 python 对象

c# - Sitecore - 在功能区中隐藏按钮

c# - 为什么不能设置公共(public) Var?

c# - 返回类实例的默认 ToString() c#

c# - .Net 继承 - 自动依赖引用行为问题

python - 从字典创建 SQL 查询

android - 在 webview 中显示谷歌地图而不是使用通常的 mapView 是否有性能损失