Nime Cloud
Nime Cloud

Reputation: 6395

How can I retrieve duplicate key value pairs?

    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;
    }

The exception is:

InvalidOperationException: Key 'Garanti.Oda' appears more than one time

How can I collect duplicate keys?

Upvotes: 1

Views: 433

Answers (2)

StuartLC
StuartLC

Reputation: 107267

Assuming you want to find duplicates by Key only (e.g. so that you can build a dictionary), you could GroupBy the prospective key and find all instances of more than one:

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

Or, if you want duplicates of both key and value, project and group by an anonymous class:

 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();

Upvotes: 0

Tim S.
Tim S.

Reputation: 56536

The method that you show isn't going to have a problem with multiple pairs with the same key. I assume that afterward, you're doing something like creating a dictionary of these pairs, and that's where you have a problem. 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

Instead, you need to use the pairs in a way that's friendly to duplicates, e.g. ToLookup.

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

Then, for example if the list had "a", "b" and "a", "c", then lookup["a"] gives you "b" and "c".

Upvotes: 2

Related Questions