简体   繁体   中英

How to Get all keys in Dictionary having same value without using LINQ

I have this:

Dictionary<integer, string> dictTempKeys = new Dictionary<integer, string>();

I want to select all the keys in the dictionary that contain the same value. I can do this by using LINQ as :

var duplicateValues = dictTempKeys.GroupBy(xx => xx.Value).Where(xx => xx.Count() > 1);

Answer for this with LINQ is already given here , but I dont want to use LINQ in my code, as I would be using this code in C# CLR Stored Procedure and that doesn't support LINQ. So is there any other approach I could attain this?

Here is my attempt - a generic extension method. The first foreach loop traverses the source dictionary and transforms it to a lookup where the keys are the values from the source, and the values are integers indicating the occurrence count of source's values in the source dictionary.

The second foreach loop will give you an IEnumerable using the yield return statement.

public static IEnumerable<TValue> GetNonUniqueValues<TKey, TValue>(this IDictionary<TKey, TValue> source)
{
  Dictionary<TValue, int> results = new Dictionary<TValue, int>();
  foreach (var kvp in source)
  {
    int count;
    if (results.TryGetValue(kvp.Value, out count))
    {
      count++;
    }
    else
    {
      count = 1;
    }

    results[kvp.Value] = count;
  }

  foreach (var kvp in results)
  {
    if (kvp.Value > 1)
    {
      yield return kvp.Key;
    }
  }
}

You can use a simple foreach loop and reverse your dictionary:

Dictionary<string, List<int>> keysByValue = new Dictionary<string, List<int>>();

foreach (KeyValuePair<int, string> entry in dictTempKeys {
    List<int> keys;
    bool hasKeys = keysByValue.TryGet(entry.Value, out keys);
    if (!hasKeys) {
        keys = new List<int>();
        keysByValue.Add(entry.Value, keys);
    }
    keys.Add(entry.Key);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM