-1

如何检查字典是否包含从预定义键开始的值?例如,我只想特定键之后搜索字典,而不是从第一个键开始搜索。

我怎样才能做到这一点?

4

3 回答 3

2

也许您需要的是一个OrderedDictionary,它提供对插入顺序的控制。这是一个示例,还包含一些搜索速度统计信息。

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            var startIndex = 1000000; // 00:00:00.0004876
            //var startIndex = 1;     // 00:00:00.0152319

            var searchedKey = "1";

            OrderedDictionary orderedDictionary = new OrderedDictionary();

            //populate
            for (int i = 2; i < 1000002; i++)
            {
                orderedDictionary.Add(i.ToString(), "X");
            }
            orderedDictionary.Add("1", "A");

            //copy the keys
            String[] keys = new String[1000006];
            orderedDictionary.Keys.CopyTo(keys, 0);

            //measure the time with a System.Diagnostics.StopWatch
            Stopwatch watch = new Stopwatch();
            watch.Start();

            for (int i = startIndex; i < orderedDictionary.Count; i++)
            {
                if (keys[i] == searchedKey)
                {
                    Console.WriteLine(orderedDictionary[i]);
                    break;
                }
            }
            watch.Stop();

            Console.WriteLine(watch.Elapsed);
        }
    }
}
于 2012-12-19T23:19:13.790 回答
1

如果它是常规的Dictionary<TKey, TValue>,那么您不能,除非您先对其进行排序。

您可以做的是使用SortedList<TKey, TValue>or SortedDictionary<TKey, TValue>, 两者都按键排序。

于 2012-12-19T23:42:28.527 回答
1

不确定在这种情况下字典是否最适合您使用,因为(如前所述)不能保证顺序。但是,如果您使用 aList<>您可以获得您正在寻找的行为。像这个例子:

        var items = new List<KeyValuePair<string, string>>();
        items.Add(new KeyValuePair<string, string>("A", "1"));
        items.Add(new KeyValuePair<string, string>("B", "2"));
        items.Add(new KeyValuePair<string, string>("C", "3"));
        var results = items.Skip(1).Take(1).ToList();

        MessageBox.Show(results[0].Key + " " + results[0].Value);

Skip在此示例中,使用andTake方法显示的结果消息将是“B 2” 。它“跳过”第一个“1”并“获取”下一个“1”;

编辑(重构为使用 KeyValuePair 列表而不是字符串。)

于 2012-12-19T23:11:44.767 回答