C# 如何在字典的第一个索引中插入元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8761109/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:18:57  来源:igfitidea点击:

How to insert element in first index in dictionary?

c#.netdictionary

提问by Hyman

Is there a method or technique that allows you to insert an element into a Dictionary<TKey, TValue>guaranteeing that the item is in the first index of that dictionary's KeyCollection.

是否有一种方法或技术允许您将元素插入到 Dictionary<TKey, TValue>保证该项目位于该字典 KeyCollection 的第一个索引中。

For example:

例如:

Dictionary<String, String> dic = foo.GetOutput(); 

// `dic` is something like:

// {"foo", "baa"},
// {"a", "b"}

I need something like:

我需要类似的东西:

dic.Add("key", "value", 0);
// where `0` is the index that `key` to be inserted.

foreach(KeyValuePair<String, String> key in dic) 
{
     Console.WriteLine("{0} = {1}", key.Key, key.Value);
}

Output:

输出:

key = value
foo = baa
a = b

采纳答案by Jon Hanna

By not using a dictionary.

通过不使用字典。

Dictionary<TKey, TValue>is implemented as a hash-table. The position of keys internal to the dictionary depends upon the hash-code, the means by which that hash-code was reduced further to provide an index into its internal structure, and the order of insertion in an entirely implementation-dependant way.

Dictionary<TKey, TValue>被实现为一个哈希表。字典内部键的位置取决于散列码,进一步减少散列码以提供其内部结构的索引的方法,以及以完全依赖于实现的方式插入的顺序。

This isn't the only way to implement a dictionary. SortedDictionary<TKey, TValue>uses a tree structure internally and so always keeps keys in an order. In this case we still can't insert something in the beginning, rather we insert something and it gets put in the appropriate place.

这不是实现字典的唯一方法。SortedDictionary<TKey, TValue>在内部使用树结构,因此始终按顺序保存键。在这种情况下,我们仍然不能在开头插入一些东西,而是插入一些东西并将其放在适当的位置。

If ordering is what you care about most, then you don't want a puredictionary at all. Rather you want either a List<KeyValuePair<TKey, TValue>>or you want a structure that offers both the functionality of a list and of a dictionary, which is provided by OrderedDictionary. This isn't generic, but you can easily create a generic wrapper around it (doesn't give the performance benefits of internally using generics, but does give type-safety in use).

如果排序是您最关心的,那么您根本不需要纯字典。相反,您想要一个List<KeyValuePair<TKey, TValue>>或您想要一个既提供列表功能又提供字典功能的结构,由OrderedDictionary. 这不是通用的,但您可以轻松地围绕它创建一个通用包装器(不会提供内部使用泛型的性能优势,但会提供使用中的类型安全性)。

回答by Jon Skeet

Dictionary<TKey, TValue>is inherently unordered (or rather, the ordering is unpredictable and shouldn't be relied upon). If you want some sort of ordering, you need to use a different type. It's hard to recommend any particular type without knowing more about your requirements.

Dictionary<TKey, TValue>本质上是无序的(或者更确切地说,排序是不可预测的,不应依赖)。如果您想要某种排序,则需要使用不同的类型。在不了解您的需求的情况下,很难推荐任何特定类型。

回答by Oded

The Dictionary<TKey,TValue>class does not hold items in an ordered manner, so there is no "first" item.

Dictionary<TKey,TValue>该类不保持在一个有序的方式的项目,所以没有“第一”项目。

There is a SortedDictionary<Tkey,TValue>(.NET 4.0+), which sorts by the key, but again, this is a very vague idea of "first".

有一个SortedDictionary<Tkey,TValue>(.NET 4.0+),它按键排序,但同样,这是一个非常模糊的“第一”概念。

回答by Dennis Traub

The Dictionary<TKey, TValue>can't be ordered.

Dictionary<TKey, TValue>无法下单。

You can try SortedDictionary<TKey, TValue>instead, but that one is ordered by the Key, not by a separate index.

你可以试试SortedDictionary<TKey, TValue>,但那个是按 Key 排序的,而不是按单独的索引排序。

回答by Adam Rackis

Dictionaries are unordered; elements are meant to be retrieved with a key, whose hash points to its value's location.

字典是无序的;元素意味着用一个键来检索,它的散列指向它的值的位置。

What you might want is a List <KeyValuePair>, whose elements can be inserted into a specific index.

您可能想要的是 a List <KeyValuePair>,其元素可以插入到特定索引中。

List<KeyValuePair<string, string>> list = dic.ToList();
list.Insert(0, new KeyValuePair<string, string>("a", "b"));

foreach(KeyValuePair<string, string> pair in list)
    Console.WriteLine("{0} = {1}", pair.Key, pair.Value);

回答by JaredPar

This is not possible with Dictionary<TKey, TValue>as it presents it's values in an unordered fashion when enumerated. There is SortedDictionary<TKey, TValue>which provides ordering but it does so by using an IComparer<TKey>against the key value directly. Here you want the key to be a Stringand have ordering based on an int. That is not possible with either of these types.

这是不可能的,Dictionary<TKey, TValue>因为它在枚举时以无序的方式呈现它的值。有SortedDictionary<TKey, TValue>它提供排序,但它是通过IComparer<TKey>直接使用键值来实现的。在这里,您希望密钥为 aString并基于int. 这对于这两种类型中的任何一种都是不可能的。

I think you'll need to implement a new type with these very specific semantics in them. For example.

我认为您需要实现一种新类型,其中包含这些非常具体的语义。例如。

class OrderedMap<TKey, TValue> {
  private readonly Dictionary<TKey, TValue> _map = new Dictionary<TKey, TValue>();
  private readonly List<TKey> _list = new List<TKey>();

  public void Add(TKey key, TValue value) {
    if (!_map.ContainsKey(key)) {
      _list.Add(key);
    }
    _map[key] = value;
  }

  public void Add(TKey key, TValue value, int index) {
    if (_map.ContainsKey(key)) {
      _list.Remove(key);
    }
    _map[key] = value;
    _list.Insert(index, key);
  }

  public TValue GetValue(TKey key) {
    return _map[key];
  }

  public IEnumerabe<KeyValuePair<TKey, TValue>> GetItems() {
    foreach (var key in _list) { 
      var value = _map[key];
      yield return new KeyValuePair<TKey, TValue>(key, value);
    }
  }
}

Note this does come with some non-trivial performance differences over a traditional Dictionary<TKey, TValue>. For example Addand Removeare slower.

请注意,这与传统的Dictionary<TKey, TValue>. 例如AddRemove速度较慢。

回答by RichardW1001

A Dictionaryis an un-ordered collection. You could try OrderedDictionary- http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx- which has an Insert()method which is what you're after.

ADictionary是无序集合。您可以尝试OrderedDictionary- http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx- 它有一种Insert()方法,这正是您所追求的。

回答by Elton da Costa

this is my solution, maybe not the best solution but it works. =)

这是我的解决方案,也许不是最好的解决方案,但它有效。=)

public static ComboBox FillDropDownList(Dictionary<String, String> dictionary, ComboBox dropDown, String selecione)
{
    var d = new SortedDictionary<String, String>();

    d.Add("0", selecione);

    foreach (KeyValuePair<string, string> pair in dictionary)
    {
        d.Add(pair.Key, pair.Value);
    }

    dropDown.DataSource = new BindingSource(d, null);
    dropDown.DisplayMember = "Value";
    dropDown.ValueMember = "Key";

    dropDown.SelectedIndex = 0;

    return dropDown;
}

回答by MJK

I know it is a three years old question. But found a workaround of this problem. It may help someone

我知道这是一个三年前的问题。但是找到了解决这个问题的方法。它可能会帮助某人

Dictionary<String, String> dic = foo.GetOutput();

dic = (new Dictionary<string, string> {{"key","value"}}).Concat(dic).ToDictionary(k => k.Key, v => v.Value);

This will insert the element in the beginning of dictionary :)

这将在字典的开头插入元素:)