Bir*_*iro 11 .net c# hashtable hashset data-structures
我有一个约9000个产品的列表,其中一些可能有重复.
我想用产品序列号作为密钥来制作这些产品的HashTable,这样我就可以轻松找到重复的产品.
如何在C#/ .NET中使用HashTable?HashSet会更合适吗?
最终我想要一个像这样的列表:
Key-Serial:11110 - 包含:Product1
Key-Serial:11111 - 包含:Product3,Product6,Product7
Key-Serial:11112 - 包含:Product4
Key-Serial:11113 - 包含:Product8,产品9
所以,我有一个所有产品的列表,它们按照具有重复序列号的产品进行分组.这样做的"正确"方法是什么?
pet*_*r p 11
我认为Dictionary是这类东西的推荐类.
在你的情况下,这将是这样的
Dictionary<string, List<Product>>
Run Code Online (Sandbox Code Playgroud)
(使用串行字符串作为键)
哈希表是一种字典,哈希集是一种集合.字典和集合都不能直接解决您的问题 - 您需要一个数据结构,它可以容纳一个键的多个对象.
此类数据库通常称为多重映射.您可以通过简单地使用哈希表来创建一个,其中键的类型是整数,值的类型是某种类型的集合(例如,hashsets ...).
或者,您可以查看现有的多地图解决方案,例如: .NET中的multimap.
有关使用哈希表的信息,您可以在MSDN上查看:http://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx,还有很多其他教程 - 搜索使用"HashTable"或"Dictionary".
我认为,通用词典最适合这种方式.代码可能如下所示:
var keyedProducts = new Dictionary<int,List<string>>();
foreach (var keyProductPair in keyProductPairs)
{
if (keyedProducts.Contains(keyProductPair.Key))
keyedProducts[keyProductPair.Key].Add(keyProductPair.Product);
else
keyedProducts.Add(keyProductPair.Key, new List<string>(new[]{keyProductPair.Product}));
}
Run Code Online (Sandbox Code Playgroud)
首先,您需要定义“主键”,即每个对象唯一的一组字段。我想Key-Serial会是该集合的一部分,但一定还有其他的。定义“主键”后,您可以定义一个表示 a 的结构Key Value,并将其用作包含您的产品的字典的键。
例子:
struct ProductPrimaryKey
{
public string KeySerial;
public string OtherDiscriminator;
public ProductPrimaryKey(string keySerial, string otherDiscriminator)
{
KeySerial = keySerial;
OtherDiscriminator = otherDiscriminator;
}
}
class Product
{
public string KeySerial { get; set; }
public string OtherDiscriminator { get; set; }
public int MoreData { get; set; }
}
class DataLayer
{
public Dictionary<ProductPrimaryKey, Product> DataSet
= new Dictionary<ProductPrimaryKey, Product>();
public Product GetProduct(string keySerial, string otherDiscriminator)
{
return DataSet[new ProductPrimaryKey(keySerial, otherDiscriminator)];
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20282 次 |
| 最近记录: |