Search code examples
c#linqkeyvaluepair

KeyValue Pair C#


I am trying to figure how to work with a list of KeyValuePairs in C#. I would use dictionaries but they do not allow for duplicate values.

Also the lookup which also i cannot figure out how to write the syntax.

I have seen other solutions but i am really confused on how to work with

Of course the only example i could find is with for loop, i would like to have it a little cleaner.

List<KeyValuePair<char, int>> data = new List<KeyValuePair<char, int>>();

I would like for example to do some checking before i add an element. For example: I have an array of characters, which i want to check before adding it to the my list. Can anyone tell me how to check.

char[] inputArray = input.ToCharArray();
for(int i = 0; i < inputArray.Length ; i++)
{
    if(!data.Values.Contains(inputArray[i]))
    {
        data.Add(new KeyValuePair<char,int>(inputArray[i], 1));
    }
}

The above code does not work. Could someone please help a bit with the syntax.

I did not found any concrete examples around the web. Any help is appreciated.


Solution

  • I have to say, your question is rather confusing. I think you're trying to add values to a list of KeyValuePair, if the key doesn't already exist? That doesn't seem to fit with what you say about not using a Dictionary, but here you go anyway:

    List<KeyValuePair<char, int>> data = new List<KeyValuePair<char, int>>();
    
    char[] inputArray = "my string".ToCharArray();
    foreach (var t in inputArray)
    {
        if (!data.Any(x => x.Key == t))
        {
            data.Add(new KeyValuePair<char, int>(t, 1));
        }
    }
    

    If you just want to get the unique values from inputArray, you could also just do:

    var myVals = inputArray.Distinct();
    

    And finally, if you want to get the count of each distinct character in a string, you can use:

    var counts = inputArray.GroupBy(x => x)
        .Select(group => new
        {
            Character = group.Key,
            Count = group.Count()
        });