在 Linq 中使用 SortedDictionary 并遍历它提供的 KeyValuePair 时,我可以确保复杂的 linq 查询将按升序执行它吗?这是一个简短的,虽然有点令人困惑的例子:
Random r = new Random();
//build 100 dictionaries and put them into a sorted dictionary
//with "priority" as the key and it is a number 0-99.
SortedDictionary<int, Dictionary<int, double>> sortedDict =
new SortedDictionary<int, Dictionary<int, double>>();
for (int i = 0; i < 100; i++)
{
Dictionary<int, double> dict = new Dictionary<int, double>();
//create the dictionary and a random 10 k/v pairs
for (int j = 0; j < 10; j++)
{
dict[r.Next(0, 100)] = r.NextDouble() * i * 10;
}
sortedDict[i] = dict;
}
IEnumerable<int> keys = Enumerable.Range(0, 100);
//the goal is to find the FIRST existence of the "key" inside one
//of the inner dictionaries going through the SortedDictionary IN ORDER
//this appears to work:
var qry = from key in keys
from priority in sortedDict
where priority.Value.ContainsKey(key)
let value = priority.Value[key]
group value by key into keyGroup
let firstValue = keyGroup.First()
select new { Key = keyGroup.Key, Value = firstValue };
// the result is as expected, a list of the numbers at most 0-99 and their
// value found in the dictionary with the lowest "priority"
问题:
- 它似乎有效,但我可以依靠这种行为吗?
- 这是有效的,还是小组把它扔掉了?
- 添加“sortedDict.Reverse()”是否也能正常工作?(看来)
- Plinq 将如何处理这个问题——它是否仍然保持一致?
如果不能保证这一点,我知道如何在事后将“优先级”拉入分组并按其排序。但我宁愿不...