C#关联数组

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

C# associative array

c#.netcollections

提问by Malfist

I've been using a Hashtable, but by nature, hashtables are not ordered, and I need to keep everything in order as I add them (because I want to pull them out in the same order). Forexample if I do:

我一直在使用哈希表,但本质上,哈希表不是有序的,我需要在添加它们时将所有内容保持有序(因为我想以相同的顺序将它们拉出)。例如,如果我这样做:

pages["date"] = new FreeDateControl("Date:", false, true, false);
pages["plaintiff"] = new FreeTextboxControl("Primary Plaintiff:", true, true, false);
pages["loaned"] = new FreeTextboxControl("Amount Loaned:", true, true, false);
pages["witness"] = new FreeTextboxControl("EKFG Witness:", true, true, false);

And when I do a foreach I want to be able to get it in the order of:

当我执行 foreach 时,我希望能够按以下顺序获取它:

pages["date"]  
pages["plaintiff"]  
pages["loaned"]  
pages["witness"] 

How can I do this?

我怎样才能做到这一点?

采纳答案by LBushkin

I believe that .NET has the OrderedDictionaryclass to deal with this. It is not generic, but it can serve as a decent Hashtable substitute - if you don't care about strict type safety.

我相信 .NETOrderedDictionary可以处理这个问题。它不是通用的,但它可以作为一个不错的 Hashtable 替代品——如果你不关心严格的类型安全。

I've written a generic wrapper around this class, which I would be willing to share.

我已经围绕这个类编写了一个通用包装器,我愿意分享它。

http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx

http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx

回答by Jon Skeet

EDIT: LBushkin is right - OrderedDictionarylooks like it does the trick, albeit in a non-generic way. It's funny how many specialized collections there are which don't have generic equivalents :( (It would make sense for Malfist to change the accepted answer to LBushkin's.)

编辑:LBushkin 是对的 -OrderedDictionary看起来它可以解决问题,尽管是以非通用的方式。有趣的是,有多少专门的集合没有通用的等价物:((马尔菲斯特将公认的答案更改为 LBushkin 的答案是有意义的。)

(I thought that...) .NET doesn't have anything built-in to do this.

(我认为...) .NET 没有任何内置功能可以做到这一点。

Basically you'll need to keep a List<string>as well as a Dictionary<string,FreeTextboxControl>. When you add to the dictionary, add the key to the list. Then you can iterate through the list and find the keys in insertion order. You'll need to be careful when you remove or replace items though.

基本上,您需要同时保留 aList<string>Dictionary<string,FreeTextboxControl>. 添加到字典时,将键添加到列表中。然后您可以遍历列表并按插入顺序查找键。但是,当您移除或更换物品时,您需要小心。

回答by Patrick Karcher

There's no perfect solution before .NET 4.0. In < 3.5 You can:

在 .NET 4.0 之前没有完美的解决方案。在 < 3.5 你可以:

Use a generic SortedListwith integer key-type, and value type of the most-derived common type of your items. Define an integer value (i, let's say) and as you add each item to the SortedList, make the key i++, incrementing it's value as you go. Later, iterate over the GetValueListproperty of the sorted list. This IListproperty will yield your objects in the order you put them in, because they will be sorted by the key you used.

使用具有整数键类型的通用 SortedList和最派生的项目常见类型的值类型。定义一个整数值(假设为 i),当您将每个项目添加到 SortedList 时,将键设为 i++,并在执行过程中增加它的值。稍后,迭代 排序列表的GetValueList属性。此IList属性将按照您放入的顺序生成您的对象,因为它们将按您使用的键排序。

This is not lightening-fast, but pretty good, and generic. If you want to also access by key, you need to do something else, but I don't see that in your requirements. If you don't new to retrieve by key, and you add items in key order so the collection doesn't actually have to doits sorting, this is it.

这不是闪电般的快速,但非常好,而且通用。如果您还想通过密钥访问,则需要执行其他操作,但我在您的要求中没有看到这一点。如果您不熟悉按键检索,并且按键顺序添加项目,则集合实际上不必进行排序,就是这样。

In .NET 4.0you'll have the generic SortedSet Of T, which will be absolutely perfect for you. No tradeoffs.

.NET 4.0 中,您将拥有通用的SortedSet Of T,这对您来说绝对是完美的。没有权衡。

回答by Hiyasat

use sorted list i think it will solve your problem becuase SortedList object internally maintains two arrays to store the elements of the list; that is, one array for the keys and another array for the associated values. Each element is a key/value pair that can be accessed as a DictionaryEntry object

使用排序列表我认为它会解决您的问题,因为 SortedList 对象在内部维护两个数组来存储列表的元素;也就是说,一个数组用于键,另一个数组用于关联值。每个元素都是一个键/值对,可以作为 DictionaryEntry 对象访问

SortedList sl = new SortedList();

SortedList sl = new SortedList();

foreach(DictionaryEntry x in sl) {}

foreach(DictionaryEntry x in sl) {}

回答by HaxElit

Use the KeyedCollection

使用 KeyedCollection

Its underlying base is a List but provides a dictionary lookup based on key. In this case your key is the strings. So as long as you aren't adding the same key twice you are fine.

它的底层基础是一个列表,但提供基于键的字典查找。在这种情况下,您的关键是字符串。因此,只要您没有两次添加相同的密钥,就可以了。

http://msdn.microsoft.com/en-us/library/ms132438.aspx

http://msdn.microsoft.com/en-us/library/ms132438.aspx

回答by Neil

As Haxelit suggests, you might derive from KeyedCollection<TKey, TValue>. It actually uses a List underneath until you hit a certain threshold value, and then it maintains both a List and a Dictionary. If you can use a function to derive one of your keys from one of your values, then this is an easy solution. If not, then it gets pretty messy.

正如 Haxelit 所建议的,您可能从KeyedCollection<TKey, TValue>. 它实际上使用下面的列表,直到您达到某个阈值,然后它同时维护一个列表和一个字典。如果您可以使用函数从您的一个值中派生出您的一个键,那么这是一个简单的解决方案。如果没有,那么它会变得非常混乱。

回答by Mamoon ur Rasheed

The best way is to use the C# indexers. It is configurable to anything we like. We can pass an int, enum, long, doubleor anything we like.

最好的方法是使用 C# 索引器。它可以配置为我们喜欢的任何东西。我们可以通过一个intenumlongdouble或任何我们喜欢。

Just have to create a class and give it indexers and configure input and output parameters. It is a little more work but I think this is the only right way.

只需要创建一个类并为其提供索引器并配置输入和输出参数。这需要更多的工作,但我认为这是唯一正确的方法。

Please see this MSDN linkfor more information how to use it.

有关如何使用它的更多信息,请参阅此MSDN 链接

回答by Jessie Plusplus

One alternative is to keep your ordered key values in an ordered structure like a List, the rest being still stored in a dictionnary.

一种替代方法是将有序键值保存在像列表这样的有序结构中,其余的仍然存储在字典中。

Then, when you need to access your data, just go through your sorted List and query your dictionnary along the way.

然后,当您需要访问您的数据时,只需浏览您的排序列表并一路查询您的字典。