0

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"

質問):

  1. 動作しているように見えますが、この動作に頼ることはできますか?
  2. これは効率的ですか、それともグループはそれを捨てますか?
  3. 「sortedDict.Reverse()」を追加しても正しく機能しますか? (ように見える)
  4. PLinq はこれをどのように処理しますか?それでも一貫性は保たれますか?

これが保証されない場合は、「優先度」をグループ化して、事後に並べ替える方法を知っています。しかし、私はむしろしたくない...

4

3 に答える 3

1

これは、どのlinqメソッドが順序を保持するかについての答えです。

クエリを見ると、次のように見えます。

  keys.SelectMany(...)
    .Where(...)
    .GroupBy(...)
    .Select(g => g.First())
    .Select(...);

これらはすべて、何らかの方法で順序を維持します。

于 2009-02-11T23:45:06.910 に答える
0
  1. はい、できます。SortedDictionary には、ソートを解除する方法がありません。例外がスローされても、ソートされたままになることが保証されています
  2. 並べ替えが効率的です。どのタイプが使用されているかなどのドメインの知識があれば、より効率的に行うことができますが、それははるかに多く、99,99% のケースでは価値がありません。
  3. はい:)
  4. 私が間違っていたようです.plinqは注文に問題があります. そのためのジョンの投稿を参照してください
于 2009-02-11T19:51:48.830 に答える