2

同じ鍵を持てません。しかし、単純な(そして効果的な)解決策は、キーの後に接尾辞を付けます。

しかし、私はforeachにいるので、重複したキーに数字のサフィックスを追加するための高速でクリーンな方法を考えていました。

例えば:

私のforeachはそれです:

foreach (Item item in items) {
    dic.Add(item.SomeKey, item.SomeValue);
}

しかし、重複したキーは必要ないので、SomeKeyを「処理」する必要がありますOriginResult

SomeKeyオリジン:key, clave, clave, chave, chave, chave
SomeKey結果:key, clave, clave1, chave, chave1, chave2


編集:@KooKizへの私の答えは質問をよりよく説明します。

重複するエントリはほとんどありません。方法を理解しようとしていますthen increment the suffix until you find no item。車輪の再発明のように聞こえるので、誰かがそれを行うための良い方法を知っているかどうか疑問に思いました

4

3 に答える 3

2

それは最速ではないかもしれませんが、私が考えることができるより読みやすいです:

        var source = new List<Tuple<string, string>>
        {
            new Tuple<string, string>("a", "a"),
            new Tuple<string, string>("a", "b"),
            new Tuple<string, string>("b", "c"),
            new Tuple<string, string>("b", "d"),
        };

        var groups = source.GroupBy(t => t.Item1, t => t.Item2);

        var result = new Dictionary<string, string>();

        foreach (var group in groups)
        {
            int index = 0;

            foreach (var value in group)
            {
                string key = group.Key;

                if (index > 0)
                {
                    key += index;
                }

                result.Add(key, value);

                index++;
            }
        }

        foreach (var kvp in result)
        {
            Console.WriteLine("{0} => {1}", kvp.Key, kvp.Value);
        }
于 2011-11-24T13:24:28.537 に答える
1

複数の「サブ」アイテムを含むキーが必要な場合は、これを試してください

Dictionary<string, List<string>> myList = new Dictionary<string, List<string>>();
foreach (Item item in items)
{
    if (myList[item.SomeKey] == null)
        myList.Add(item.SomeKey, new List<string>());
    myList[item.SomeKey].Add(item.SomeValue);
} 
于 2011-11-24T12:59:04.247 に答える
0
var a = items.GroupBy(p => p.SomeKey)
.SelectMany(q => q.Select((value, index) =>
 new Item { SomeKey = (q.Count() > 1 && index > 0) ? value.SomeKey + (index) :  
         value.SomeKey, SomeValue = value.SomeValue }))
.ToDictionary(p => p.SomeKey, q => q.SomeValue);
于 2011-11-24T13:21:45.153 に答える