如何检索重复的键值对?

时间:2014-12-01 21:02:15

标签: c#

    public static IEnumerable<KeyValuePair<string, string>> GetGroupKeyValuePairs(string category)
    {
        var list = new List<KeyValuePair<string, string>>();

        using (DataConnection connection = new DataConnection())
        {
            List<KeyValuePair<string,string>> settings = connection.Get<Settings>()
                .Where(a => a.Category == category )
                .Select(pair => new KeyValuePair<string,string>(pair.TheName, pair.TheValue))
                .ToList();

            list = settings;

        }

        return list;
    }

例外是:

  

InvalidOperationException异常:   关键'Garanti.Oda'出现不止一次

如何收集重复的密钥?

2 个答案:

答案 0 :(得分:2)

您显示的方法不会出现多个具有相同键的对的问题。我假设之后,你正在做一些像创建这些对的字典,以及你遇到问题的地方。 E.g。

var pairs = GetGroupKeyValuePairs("some category");
var dict = new Dictionary<string, string>();
foreach (var pair in pairs)
    dict.Add(pair.Key, pair.Value); // exception when it hits a duplicate

相反,您需要以对重复方式友好的方式使用对,例如ToLookup

var pairs = GetGroupKeyValuePairs("some category");
var lookup = pairs.ToLookup(x => x.Key, x => x.Value);

然后,例如,如果列表中包含"a", "b""a", "c",则lookup["a"]会为您提供"b""c"

答案 1 :(得分:0)

假设您只想通过Key查找重复项(例如,以便您可以构建字典),您可以GroupBy预期密钥并查找多个实例:

 var dupeSettings = connection.Get<Settings>()
            .Where(a => a.Category == category)
            .GroupBy(a => a.TheName)
            .Where(grp => grp.Count() > 1)
            .Select(dupe => dupe.Key)
            .ToList();

或者,如果您希望重复键,请按匿名类进行项目和分组:

 var dupeSettings = connection.Get<Settings>()
            .Where(a => a.Category == category)
            .GroupBy(a => new {a.TheName, a.TheValue})
            .Where(grp => grp.Count() > 1)
            .Select(dupe => dupe.Key) // Key.TheName, Key.TheValue
            .ToList();
相关问题