我有一个本质上是名称值对的锯齿状数组 - 我需要从中生成一组唯一的名称值。锯齿状数组大约有 86,000 x 11 个值。
对我来说,我必须以何种方式存储名称值对(单个字符串“name=value”或专用类,例如 KeyValuePair)并不重要。
附加信息:有 40 个不同的名称和更多的不同值 - 可能在 10,000 个值范围内。
我正在使用 C# 和 .NET 2.0(性能很差,我认为将整个锯齿状数组插入 sql 数据库并从那里进行选择可能会更好)。
下面是我当前使用的代码:
List<List<KeyValuePair<string,string>>> vehicleList = retriever.GetVehicles();
this.statsLabel.Text = "Unique Vehicles: " + vehicleList.Count;
Dictionary<KeyValuePair<string, string>, int> uniqueProperties = new Dictionary<KeyValuePair<string, string>, int>();
foreach (List<KeyValuePair<string, string>> vehicle in vehicleList)
{
foreach (KeyValuePair<string, string> property in vehicle)
{
if (!uniqueProperties.ContainsKey(property))
{
uniqueProperties.Add(property, 0);
}
}
}
this.statsLabel.Text += "\rUnique Properties: " + uniqueProperties.Count;
最佳答案
我让它运行了 0.34 秒,从 9 分钟以上下降
问题出在比较 KeyValuePair 结构时。 我通过编写比较器对象并将其实例传递给 Dictionary 来解决这个问题。
据我所知,KeyValuePair.GetHashCode() 返回它的 Key
对象(在本例中是最不唯一的对象)的哈希码。
当字典添加(并检查是否存在)每个项目时,它同时使用 Equals 和 GetHashCode 函数,但当哈希码不那么唯一时必须依赖 Equals 函数。
通过提供更独特的 GetHashCode 函数,它使用 Equals 函数的频率大大降低。我还优化了 Equals 函数,以便在不太独特的键之前比较更独特的值。
86,000 * 11 个具有 10,000 个唯一属性的项目使用下面的比较器对象在 0.34 秒内运行(没有比较器对象需要 9 分 22 秒)
希望这有帮助:)
class StringPairComparer
: IEqualityComparer<KeyValuePair<string, string>>
{
public bool Equals(KeyValuePair<string, string> x, KeyValuePair<string, string> y)
{
return x.Value == y.Value && x.Key == y.Key;
}
public int GetHashCode(KeyValuePair<string, string> obj)
{
return (obj.Key + obj.Value).GetHashCode();
}
}
编辑:如果它只是一个字符串(而不是 KeyValuePair,其中 string = Name+Value),它的速度大约是原来的两倍。这是一个很有趣的问题,我在这上面花了太多时间faaaaaar(虽然我学会了安静一点)
关于c# - 在 .net 2 中生成唯一集的最快方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/232997/