C# 如何从字典中获取第 n 个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1172931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the nth element from a Dictionary?
提问by Adam Kane
cipher = new Dictionary<char,int>;
cipher.Add( 'a', 324 );
cipher.Add( 'b', 553 );
cipher.Add( 'c', 915 );
How to get the 2nd element? For example, I'd like something like:
如何获得第二个元素?例如,我想要这样的东西:
KeyValuePair pair = cipher[1]
Where pair contains ( 'b', 553 )
其中对包含 ( 'b', 553 )
Based on the coop's suggestion using a List, things are working:
根据 coop 使用 List 的建议,一切正常:
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 ];
Assuming that I'm correct that the items stay in the list in the order they are added, I believe that I can just use a List
as opposed to a SortedList
as suggested.
假设我正确地将项目按添加顺序保留在列表中,我相信我可以只使用 aList
而不是SortedList
建议的 a 。
采纳答案by thecoop
The problem is a Dictionary isn't sorted. What you want is a SortedList, which allows you to get values by index as well as key, although you may need to specify your own comparer in the constructor to get the sorting you want. You can then access an ordered list of the Keys and Values, and use various combinations of the IndexOfKey/IndexOfValue methods as needed.
问题是字典没有排序。您想要的是SortedList,它允许您通过索引和键获取值,尽管您可能需要在构造函数中指定自己的比较器以获得所需的排序。然后,您可以访问键和值的有序列表,并根据需要使用 IndexOfKey/IndexOfValue 方法的各种组合。
回答by Cyberherbalist
Just to cling to your original spec for a Dictionary, I slung some code and came up with:
只是为了坚持你对字典的原始规范,我抛出了一些代码并想出了:
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);
}
and it does seem to write the second item ("ball") to the console repeatably. If you wrapped it into a method call to get the nth element, it would probably work. This is pretty ugly, though. If you could do a SortedList instead, as @thecoop suggests, you'd be better off.
它似乎确实重复地将第二个项目(“球”)写入控制台。如果您将它包装到方法调用中以获取第 n 个元素,它可能会起作用。不过,这很丑陋。如果你可以做一个 SortedList ,正如@thecoop 所建议的那样,你会更好。
回答by grenade
like this:
像这样:
int n = 0;
int nthValue = cipher[cipher.Keys.ToList()[n]];
note that you will also need a reference to Linq at the top of your page...
请注意,您还需要在页面顶部引用 Linq...
using System.Linq;
回答by Jon Skeet
Do you actually need to look up by the key? If not, use a List<KeyValuePair<char, int>>
(or better yet, create a type to encapsulate the char and the int).
你真的需要按钥匙查找吗?如果没有,请使用 a List<KeyValuePair<char, int>>
(或者更好的是,创建一个类型来封装 char 和 int)。
Dictionaries aren't inherently sorted - the dictionary implementations which aresorted in .NET are sorted by key, not by insertion order.
字典本身不是排序的 -在 .NET 中排序的字典实现是按键排序的,而不是按插入顺序排序。
If you need to access the collection by both insertion order and key, I'd recommend encapsulating a List and a Dictionary in a single collection type.
如果您需要通过插入顺序和键访问集合,我建议将 List 和 Dictionary 封装在单个集合类型中。
Alternatively, if the list is going to be quite short, allow lookup by index just by doing a linear search...
或者,如果列表会很短,只需通过线性搜索允许按索引查找...
回答by vipw
There was a dupe of this question asked here: How to retrieve Nth item in dictionary?. It should be closed soon, but I noticed that the answers here are missing the new OrderedDictionary class.
这里有人问了这个问题:如何检索字典中的第 N 个项目?. 它应该很快关闭,但我注意到这里的答案缺少新的 OrderedDictionary 类。
There is now (as of .NET 4), an OrderedDictionaryclass. This allows fast lookups while providing ordering. The Item(Int32) method returns the nth element.
现在(从 .NET 4 开始)有一个OrderedDictionary类。这允许在提供排序的同时进行快速查找。Item(Int32) 方法返回第 n 个元素。
回答by Olioul Islam Rahi
You can apply the following LINQ query on your 'cipher' Dictionary
您可以在“密码”上应用以下 LINQ 查询 Dictionary
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
回答by Sahil Mukheja
You can use ElementAt()
like this:
你可以这样使用ElementAt()
:
cipher.ElementAt(index);
Its better than than the Select
option because this way you don't have to loop through the dictionary:
它比Select
选项更好,因为这样您就不必遍历字典:
documentation
文件
/// <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>
回答by tony722
This is an old question, but it was helpful to me. Here's an implementation that I used. I wanted the nth element to be based on the insertion order.
这是一个老问题,但对我很有帮助。这是我使用的一个实现。我希望第 n 个元素基于插入顺序。
public class IndexedDictionary<TKey, TValue> : IEnumerable<TValue> {
private List<TValue> list = new List<TValue>();
private Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();
public TValue this[int index] { get { return list[index]; } }
public TValue this[TKey key] { get { return dict[key]; } }
public Dictionary<TKey, TValue>.KeyCollection Keys { get { return dict.Keys; } }
public int Count { get { return list.Count; } }
public int IndexOf(TValue item) { return list.IndexOf(item); }
public int IndexOfKey(TKey key) { return list.IndexOf(dict[key]); }
public void Add(TKey key, TValue value) {
list.Add(value);
dict.Add(key, value);
}
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() {
return list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return list.GetEnumerator();
}
}