我想要一个集合,将浮点数的键值对存储到整数(浮点数是关键).然后我想找到具有最小数字的键值对.所以,我基本上想要使用最低的关联浮点值来获取int值.
也许是一个集合,它根据键保持它们的顺序,并允许我索引它,以便在索引0抓取对象是合适的?我不知道从哪里开始寻找这个.
你可以试试SortedDictionary.如果你打电话给.Keys,你将得到一个有序的密钥集合.然后,您可以使用LINQ .First()函数获取集合中的第一个键,例如:
var mySortedDictionary = new SortedDictionary<float, int>();
// ...
// Add some values to dictionary
// ...
// Note, you will need the System.Linq namespace for First()
float firstKey = mySortedDictionary.Keys.First();
int firstValue = mySortedDictionary[firstKey];
// If you just need the value:
int firstValue2 = mySortedDictionary.Values.First();
Run Code Online (Sandbox Code Playgroud)
如果需要获取第一个或最后一个键以外的键,可以使用LINQ .ToArray()或.ToList()函数返回可索引的数组或列表,如下所示:
float[] indexableKeys = mySortedDictionary.Keys.ToArray();
int[] indexableValues = mySortedDictionary.Values.ToArray();
Run Code Online (Sandbox Code Playgroud)
此外,以下代码将遍历集合并按排序顺序为您提供所有KeyValuePairs:
foreach (var pair in mySortedDictionary)
{
int key = pair.Key;
// Do stuff with key...
object value = pair.Value;
// Do stuff with value...
}
Run Code Online (Sandbox Code Playgroud)
作为替代方案,您还可以使用SortedList,它是可索引的.要使用它,您只需要以下代码:
var mySortedList = new SortedList<float, int>();
// ...
// Add some values to sortedlist
// ...
int firstValue = mySortedList.Values[0];
Run Code Online (Sandbox Code Playgroud)
注意:我没有机会对这些中的任何一个进行基准测试,所以我不确定哪个会表现更好.使用已排序的集合肯定比常规集合具有更多的开销.如果您只需要知道哪个键是第一个键,那么最好创建一个包含Dictionary的自定义类和一个private float first;存储哪个键是第一个键的私有字段.当您添加到该类时,它会将KeyValuePair添加到字典中并检查该键是否小于您的first变量(或者如果字典中没有键).如果是,则设置first为新密钥.删除值时,再次将其从"词典"中删除.如果键等于您的first值,那么您需要对Dictionary.Keys集合进行排序并首先找到新的.这可能会表现最好,但您必须自己编写课程.
注意: 在做了一些基准测试后,我发现SortedDictionary的删除速度更快,但SortedList更快,可以按键添加和索引. 这是通过使用1,000,000个keyValue对填充常规字典来完成的(键被洗牌以便以随机顺序输入).然后我:
添加或索引时SortedList的速度大约是其两倍,但删除每个元素的时间大约是其1000倍.