找到Hashtable中的最小数字? [英] find minimum number in a Hashtable?
问题描述
我可以在哈希表中找到最小的数字吗?
i am存储,例如Hashtable.Add(carName,carPrice)和我需要找到价格最低的那个
Is it possible for me to find the smallest number in a hashtable?
i am storing, for example Hashtable.Add("carName", carPrice) and I need to find one that has lowest price
推荐答案
如果您放入Hashtable的值都是相同的类型,您可以考虑使用System.Collections.Generic.Dictionary< TKey,TValue>
- 其中TKey
和TValue
是示例中键和值的类型(string
,或许,decimal
)。 />
如果你这样做,那么值集合将是强类型的,你可以轻松地使用Linq来获得最小值:
If the values you're putting into the Hashtable are all of the same type, you might consider usingSystem.Collections.Generic.Dictionary<TKey, TValue>
- whereTKey
andTValue
are the types of the key and value (string
and, perhaps,decimal
in your example).
If you do this, then the values collection will be strongly typed and you can easily use Linq to get the minimum value:
var hash = new Dictionary<string, decimal>();
// ... add values
var minPrice = hash.Values.Min();
当然,如果你正在混合价值观在集合中,您需要使用散列表(或值类型为 object
的字典),您将不得不使用其他一些Linq方法来消除非数字值,或确保在尝试获取最小值之前将所有值转换为通用数字类型。查看 System.Linq.Enumerable.Select()
,将值转换为公共类型, System.Linq.Enumerable.OfType< TFilteredType>
仅用于检索 TFilteredType
的值。
原始示例可能看起来像一个或以下其他:
Of course, if you're mixing values in the collection, you'll need to use a hashtable (or a Dictionary where the value type is object
) and you'll have to use some of the other Linq methods to eliminate non-numeric values, or to ensure that all values are converted to a common numeric type before you attempt to take the minimum value. Look into System.Linq.Enumerable.Select()
for converting values to a common type and System.Linq.Enumerable.OfType<TFilteredType>
for retrieving only the values of TFilteredType
.
A crude example might look like one or the other of the following:
// use this if you're only interested in values that are decimals
var minPrice = hash.Values.OfType<decimal>().Min();
// Use this if you need to convert values to decimal, where possible,
// and ignore them otherwise
minPrice = hash.Values.Select(v => v.ToString()) // Work with string representation of the value
.Where(v => { // Ignore it if it's not convertible to decimal
decimal result;
return decimal.TryParse(v, out result);
})
.Select(v => decimal.Parse(v)) // Convert to decimal: we've already eliminated non-convertible values
.Min(); // Now get the minimum value
您必须迭代所有项目,找出价格最低的项目。
You have to iterate on all the items, to find out the one with lowest price.
这篇关于找到Hashtable中的最小数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!