【问题标题】:How can I retrieve duplicate key value pairs?如何检索重复的键值对?
【发布时间】:2014-12-02 05:41:12
【问题描述】:
    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;
    }

例外是:

无效操作异常: 键“Garanti.Oda”出现不止一次

如何收集重复的密钥?

【问题讨论】:

  • @mybirthname:OP 应该能够使用相同的密钥创建尽可能多的 KeyValuePair 实例,并且他们应该能够将尽可能多的实例添加到简单的 List 中他们喜欢。该结构本身没有任何东西可以阻止同一密钥同时存在于多个KeyValuePair 结构中。
  • @O.R.Mapper 我将阅读有关键值对的信息以检查您写的内容,我使用它们 2-3 次可能是我的错误。谢谢!
  • @mybirthname: dotnetfiddle.net/SElgkq
  • @OrelEraki:你是怎么知道他们“不能”的?另外,您指的是什么NameValuePair 类型?来自Microsoft.Build.Framework.XamlTypes 的那个?还是来自Microsoft.Rtc.Signaling 的那个?这些听起来都不应该或不能从 3rd 方通用代码中使用。
  • @O.R.Mapper 绝对正确..

标签: c#


【解决方案1】:

您展示的方法对于具有相同密钥的多对不会有问题。我假设之后,您正在做类似创建这些对的字典之类的事情,这就是您遇到问题的地方。例如

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"

【讨论】:

  • 然后我使用 List.Distinct() 方法稍后删除重复项。
【解决方案2】:

假设您只想通过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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 2023-04-04
    • 2014-12-07
    • 1970-01-01
    • 2022-01-06
    • 2012-12-08
    • 1970-01-01
    相关资源
    最近更新 更多