[英]Random insert, Random get C# Collection
I need a C# collection from which I can as quickly as possible pick out a random element, but also add new elements to. 我需要一个C#集合,可以从中尽快选择一个随机元素,还可以向其中添加新元素。 It is for a scrabble bag of letter blocks.
它是用于拼字游戏袋的字母块。 Which one should I use?
我应该使用哪一个?
You can use List<T>
. 您可以使用
List<T>
。 It depends what you want to keep in that list too. 这也取决于您要保留在该列表中的内容。
Anything implementing IList
(or, more probably IList<T>
) as these can be referenced by index. 任何实现
IList
东西(或更可能是IList<T>
)都可以通过索引引用。 Its very easy to pick a random number in the range 0 < n < list.Count-1
and get that item from the list. 选择
0 < n < list.Count-1
范围内的随机数并从列表中获取该项目非常容易。
eg/ 例如/
// assumes 'random' is an instance of System.Random
myRandomElement = myList[random.Next(0,myList.Count-1)]
The Dictionary generic class provides a mapping from a set of keys to a set of values.
Dictionary泛型类提供了从一组键到一组值的映射。 Each addition to the dictionary consists of a value and its associated key.
字典的每个加法项都包含一个值及其关联的键。 Retrieving a value by using its key is very fast, close to O(1) , because the Dictionary class is implemented as a hash table.
通过使用键的值检索值非常快,接近O(1) ,因为Dictionary类是作为哈希表实现的。
Edit: Ok, I thought you need to specify keys or something. 编辑:好的,我认为您需要指定键或其他内容。
What is wrong with List<> ? List <>有什么问题?
如果您想提高速度,我建议您使用Dictionairy
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.