Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在.NET中选择好的动态数组数据类型_C#_Asp.net_.net_Arrays - Fatal编程技术网

C# 在.NET中选择好的动态数组数据类型

C# 在.NET中选择好的动态数组数据类型,c#,asp.net,.net,arrays,C#,Asp.net,.net,Arrays,我有一个经常变化的主题数据库表。假设表中有topic\u id和topic 在我的代码中,我需要记录每个主题中使用了多少次 存储每个主题的计数的好动态数组数据类型是什么 我应该使用arrayList吗 举一个如何使用它的例子会很有帮助。你可以使用字典对于任何你有键值类型的数据并且需要它的集合的地方,地图或字典将是正确的选择。我建议使用字典 Dictionary<string, int> topicCounts 或者,您可以更强烈地键入一点 Dictionary<Topic,

我有一个经常变化的主题数据库表。假设表中有topic\u id和topic

在我的代码中,我需要记录每个主题中使用了多少次

存储每个主题的计数的好动态数组数据类型是什么

我应该使用arrayList吗


举一个如何使用它的例子会很有帮助。

你可以使用字典

对于任何你有键值类型的数据并且需要它的集合的地方,地图或字典将是正确的选择。

我建议使用字典

Dictionary<string, int> topicCounts
或者,您可以更强烈地键入一点

Dictionary<Topic, int> topicCounts

然后像索引器一样访问计数

是。ArrayList是最好的

使用此命名空间可以包括ArrayList

using System.Collections;
声明一个数组列表,如下所示

ArrayList myArray = new ArrayList();
将项目添加到arraylist

myArray.Add("Value");
myArray.Remove("Value");
从arraylist中删除项

myArray.Add("Value");
myArray.Remove("Value");
一个好的选择是

Dictionary<int, int>
或者,如果您在多个线程中更新/阅读它,那么

ConcurrentDictionary<TKey, TValue>
实际上,如果您喜欢lambdas,ConcurrentDictionary有一个自然线程安全的AddOrUpdate方法,在进行计数时非常方便;如果没有常规字典中的多个调用,我想不出一种方法来实现这一点

列表可用于存储列表

三元组有三个属性First、Second、Third,它们可以保存TopicID、TopicName和Count


或者,您可以创建一个自定义类来保存带有ID、名称、计数属性的主题信息。

正如其他答案所指出的,字典可能是一个不错的选择

假设:

您的主题id是一个int数据类型。 用法示例:

Dictionary<int, int> occurrencesOfTopicsByTopicID = new Dictionary<int, int>();

// The following code increments the number of occurrences of a specific topic,
// identified by a variable named "idOfTopic", by one.

int occurrences;

// Try to get the current count of occurrences for this topic.
// If this topic has not occurred previously,
// then there might not be an entry in the dictionary.
if (occurrencesOfTopicsByTopicID.TryGetValue(idOfTopic, out occurrences))
{
    // This topic already exists in the dictionary,
    // so just update the associated occurrence count by one
    occurrencesOfTopicsByTopicID[idOfTopic] = occurrences + 1;
}
else
{
    // This is the first occurrence of this topic,
    // so add a new entry to the dictionary with an occurrence count of one.
    occurrencesOfTopicsByTopicID.Add(idOfTopic, 1);
}
IDictionary的一个实现,其中TKey与您将查找的类型(可能是Topic,也可能是int)相匹配


对于大多数用途来说,最简单、最快的是字典。但是,由于这是ASP.NET,而且您似乎正在使用它进行某种缓存,因此您可能需要从多个线程访问此集合。字典对于多个并发读卡器来说是安全的,所以如果更新不频繁,那么使用ReaderWriterLockSlim保护字典可能是一个不错的选择。如果您可以让多个线程同时尝试更新,那么您可以从ConcurrentDictionary或我自己的中获得更好的性能。

相关:为什么您认为这是最好的?我认为这根本不是正确的选择ArrayList不是最好的这更多是个人意见我会使用字典一旦你有了它你需要对计数做什么吗?您是否需要将计数存储在某个位置,或者只是根据需要动态计算?