0

可能重复:
如何从字典中获取第 n 个元素?

我必须从字典中获取键名。 如何从字典中获取第 n 个元素?补救措施不是。

Dictionary<string, string> ListDegree= new Dictionary<string,int>();
ListDegree.Add( 'ali', 49);
ListDegree.Add( 'veli', 50);

我想得到带有索引的“ali”。以下代码获取值“324”。我该怎么办?

int i=-1;
foreach (var item in ListDegree)
{
    i++;
}
if (i == -1)
    mf.txtLog.AppendText("Error: \"Code = 1\"");
else
    mf.txtLog.AppendText("Error: \""+ListDegree[ListDegree.Keys.ToList()
        [i]].ToString()+"\"");
4

4 回答 4

1
public TKey GetNthKeyOf<TKey,TValue>(Dictionary<TKey,TValue> dic, n)
{
    int i = 0;
    foreach(KeyValuePair kv in dic)
    {
       if (i==n) return kv.Key;
       i++;
    }
    throw new IndexOutOfRangeException();
}

*编辑*

public static class DicExt
{
    public static TKey GetNthKeyOf<TKey,TValue>(this Dictionary<TKey,TValue> dic, n)
    {
        int i = 0;
        foreach(KeyValuePair kv in dic)
        {
           if (i==n) return kv.Key;
           i++;
        }
        throw new IndexOutOfRangeException();
    }
}

*编辑 2 * 正如@tomfanning 所说,Dictionary 不提供订购保证,所以我的解决方案是假的解决方案,没有任何意义。

于 2012-11-28T10:03:11.117 回答
1

正如Oded指出的那样,您为什么不使用OrderedDictionary?这是一个示例:

using System;
using System.Collections.Specialized;

namespace ConsoleApplication1
{
    class ListDegree:OrderedDictionary
    {
    }

    class Program
    {
        public static void Main()
        {
            var _listDegree = new ListDegree();
            _listDegree.Add("ali", 324);
            _listDegree.Add("veli", 553);

            int i = -1;
            foreach (var item in _listDegree)
            {
                i++;
            }
            if (i == -1)
                Console.WriteLine("Error: \"Code = 1\"");
            else
                Console.WriteLine("Error: \"" + _listDegree[i] + "\"");
        }
    }
}
于 2012-11-28T10:04:29.777 回答
0
mf.txtLog.AppendText("Hata: \"" + anchorPatternClass.GetNthKeyOf(i).ToString() + "\"");
......
    public TKey GetNthKeyOf<TKey,TValue>(Dictionary<TKey,TValue> dic, n)
    {
        int i = 0;
        foreach(KeyValuePair kv in dic)
        {
           if (i==n) return kv.Key;
           i++;
        }
        throw new IndexOutOfRangeException();
    }
于 2012-11-28T10:29:38.613 回答
0

虽然通过第 N 个元素访问字典看起来很奇怪,但它可能是这样的

int N=.....
var val = ListDegree.SkipWhile((kv, inx) => inx != N)
                    .Select(kv => kv.Value)
                    .First();
于 2012-11-28T10:49:48.420 回答