如何从字典中获取第n个元素键名?

时间:2012-11-28 09:54:47

标签: c# list dictionary

  

可能重复:
  How do I get the nth element from a Dictionary?

我必须从字典中获取密钥名称。 How do I get the nth element from a Dictionary?补救措施不是。

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 个答案:

答案 0 :(得分: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不提供订购保证,所以我的解决方案是假的解决方案,并没有意义。

答案 1 :(得分: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] + "\"");
        }
    }
}

答案 2 :(得分: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();
    }

答案 3 :(得分:0)

虽然通过Nth元素访问字典看起来很奇怪,但这可能是

int N=.....
var val = ListDegree.SkipWhile((kv, inx) => inx != N)
                    .Select(kv => kv.Value)
                    .First();