C# 如何从字典中获取第n个元素?

C# 如何从字典中获取第n个元素?,c#,dictionary,C#,Dictionary,其中一对包含('b',553) 根据合作社使用列表的建议,情况正在好转: KeyValuePair pair = cipher[1] List cipher=newlist(); 添加(新的KeyValuePair('a',324)); 添加(新的KeyValuePair('b',553)); 添加(新的KeyValuePair('c',915)); KeyValuePair=密码[1]; 假设我正确地认为项目按添加顺序保留在列表中,我相信我可以使用列表,而不是建议的排序列表。问题是字典没

其中一对包含
('b',553)


根据合作社使用列表的建议,情况正在好转:

KeyValuePair pair = cipher[1]
List cipher=newlist();
添加(新的KeyValuePair('a',324));
添加(新的KeyValuePair('b',553));
添加(新的KeyValuePair('c',915));
KeyValuePair=密码[1];

假设我正确地认为项目按添加顺序保留在列表中,我相信我可以使用
列表
,而不是建议的
排序列表。

问题是字典没有排序。您需要的是一个,它允许您按索引和键获取值,尽管您可能需要在构造函数中指定自己的比较器来获取所需的排序。然后,您可以访问键和值的有序列表,并根据需要使用IndexOfKey/IndexOfValue方法的各种组合。

为了保持字典的原始规范,我附带了一些代码,并提出了:

List<KeyValuePair<char, int>> cipher = new List<KeyValuePair<char, int>>();
cipher.Add( new KeyValuePair<char, int>( 'a', 324 ) );
cipher.Add( new KeyValuePair<char, int>( 'b', 553 ) );
cipher.Add( new KeyValuePair<char, int>( 'c', 915 ) );

KeyValuePair<char, int> pair = cipher[ 1 ];
Dictionary d=newdictionary();
d、 添加(“a”、“苹果”);
d、 添加(“b”、“ball”);
d、 添加(“c”、“cat”);
d、 添加(“d”、“狗”);
int t=0;
foreach(d.Values中的字符串s)
{
t++;
如果(t==2)控制台写入线;
}
而且它似乎可以重复地将第二项(“球”)写入控制台。如果您将其包装到方法调用中以获取第n个元素,它可能会工作。不过这很难看。如果你能像@thecoop建议的那样做一个分类列表,你会更好。

像这样:

Dictionary<string, string> d = new Dictionary<string, string>();

d.Add("a", "apple");
d.Add("b", "ball");
d.Add("c", "cat");
d.Add("d", "dog");

int t = 0;
foreach (string s in d.Values)
{
    t++;
    if (t == 2) Console.WriteLine(s);
}
        var cipher = new Dictionary<char, int>();
        cipher.Add('a', 324);
        cipher.Add('b', 553);
        cipher.Add('c', 915);

        var nThValue = cipher.Select((Val, Index) => new { Val, Index })
            .Single(viPair => viPair.Index == 1)   //Selecting dictionary item with it's index using index
            .Val                                   //Extracting KeyValuePair from dictionary item
            .Value;                                //Extracting Value from KeyValuePair
请注意,您还需要在页面顶部引用Linq

int n = 0;
int nthValue = cipher[cipher.Keys.ToList()[n]];

你真的需要按钥匙查吗?如果没有,请使用
列表(或者更好的是,创建一个类型来封装char和int)

字典并不是固有的排序——在.NET中排序的字典实现是按键排序的,而不是按插入顺序排序的

/// <summary>Returns the element at a specified index in a sequence.</summary>
/// <returns>The element at the specified position in the source sequence.</returns>
/// <param name="source">An <see cref="T:System.Collections.Generic.IEnumerable`1" /> to return an element from.</param>
/// <param name="index">The zero-based index of the element to retrieve.</param>
/// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="source" /> is null.</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index" /> is less than 0 or greater than or equal to the number of elements in <paramref name="source" />.</exception>
如果需要通过插入顺序和键访问集合,我建议将列表和字典封装在单个集合类型中


或者,如果列表很短,只需进行线性搜索即可通过索引进行查找…

这里有一个重复的问题:。它应该很快关闭,但我注意到这里的答案缺少新的OrderedDictionary类


现在(从.NET4开始)有一个类。这允许快速查找,同时提供订购。Item(Int32)方法返回第n个元素。

您可以在“cipher”
字典上应用以下LINQ查询

using System.Linq;
var cipher=newdictionary();
加上('a',324);
加上('b',553);
加上('c',915);
var nThValue=cipher.Select((Val,Index)=>new{Val,Index})
.Single(viPair=>viPair.Index==1)//使用索引选择具有索引的字典项
.Val//从字典项中提取KeyValuePair
.价值//从KeyValuePair提取值

您可以像这样使用
ElementAt()

Dictionary<string, string> d = new Dictionary<string, string>();

d.Add("a", "apple");
d.Add("b", "ball");
d.Add("c", "cat");
d.Add("d", "dog");

int t = 0;
foreach (string s in d.Values)
{
    t++;
    if (t == 2) Console.WriteLine(s);
}
        var cipher = new Dictionary<char, int>();
        cipher.Add('a', 324);
        cipher.Add('b', 553);
        cipher.Add('c', 915);

        var nThValue = cipher.Select((Val, Index) => new { Val, Index })
            .Single(viPair => viPair.Index == 1)   //Selecting dictionary item with it's index using index
            .Val                                   //Extracting KeyValuePair from dictionary item
            .Value;                                //Extracting Value from KeyValuePair
它比
选择
选项要好,因为这样您就不必在字典中循环:

文档
///返回序列中指定索引处的元素。
///源序列中指定位置的元素。
///要从中返回元素的。
///要检索的元素的从零开始的索引。
///的元素的类型。
/// 
///是空的。
/// 
///小于0或大于等于中的元素数。

这是一个老问题,但它对我很有帮助。这是我使用的一个实现。我希望第n个元素基于插入顺序

/// <summary>Returns the element at a specified index in a sequence.</summary>
/// <returns>The element at the specified position in the source sequence.</returns>
/// <param name="source">An <see cref="T:System.Collections.Generic.IEnumerable`1" /> to return an element from.</param>
/// <param name="index">The zero-based index of the element to retrieve.</param>
/// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="source" /> is null.</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index" /> is less than 0 or greater than or equal to the number of elements in <paramref name="source" />.</exception>
公共类索引字典:IEnumerable{
私有列表=新列表();
专用字典dict=新字典();
public TValue this[int index]{get{return list[index];}
public TValue this[TKey]{get{return dict[key];}
public Dictionary.KeyCollection密钥{get{return dict.Keys;}}
公共整数计数{get{return list.Count;}}
public int IndexOf(TValue项){return list.IndexOf(项);}
public int IndexOfKey(TKey){return list.IndexOf(dict[key]);}
公共无效添加(TKey键,TValue值){
列表。添加(值);
dict.Add(键、值);
}
IEnumerator IEnumerable.GetEnumerator(){
返回list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator(){
返回list.GetEnumerator();
}
}

您可以使用
ElementAt(int)
扩展方法,但正如该公司所说,它没有排序,因此无法保证两次连续调用之间的结果相同。字典是否排序无关紧要,您只需要保证第n个键将一致地返回第n个值,而且确实如此。请看下面我的答案。@Gavimoss:不。
属性返回
IList
如果使用排序列表,更简单的方法是只对第n个键和
Cipher.GetByIndex(n)使用
Cipher.GetKey(n)
第n个值。我之所以提出这个问题,是因为我试图在一个控件上实现可访问性,该控件使用字典作为它需要绘制的项的集合。因此控件实际上需要按键查找项,但我还需要能够按索引查找项,以覆盖
AccessibleObject.GetChild(索引为整数)
。也许现在5年过去了,我终于可以承认我投了否决票,纯粹是为了让我的答案看起来比你的分数高,明目张胆地试图抢夺代表。在我的辩护中,我是SO的新手,也是一个相当棘手的人。所以,当选票过期时,也不要让一个人纠正他们的错误,所以我带着我的耻辱生活。@glande,我刚刚注意到你发自内心地承认自己有罪!我不知道乔恩