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 はこれをどのように処理しますか?それでも一貫性は保たれますか?
これが保証されない場合は、「優先度」をグループ化して、事後に並べ替える方法を知っています。しかし、私はむしろしたくない...