xglide
xglide

Reputation: 65

preventing adds of KVPs with duplicate key Values c#

I have a list of (int,int) KeyValuePairs and I want to prevent adds to this is if the key already exists. Is this function already present? or do I have to prevent the add in some other way?

EDIT: Additionally I want to be able to sort the collection by the value in ascending order. Is there a way to do that as well?

Thanks in advance!

Upvotes: 0

Views: 896

Answers (2)

Kavindu Dodanduwa
Kavindu Dodanduwa

Reputation: 13067

Instead of a List<> of KeyValuePair best approach would be to use a Dictionary, which is also a key value pair collection but with additional members.

Dictionary :

Represents a collection of keys and values.

In your case you could simply use Dictionary<int,int> , which means a dictionary with int key and int value.

Key uniqueness

Every key in a Dictionary must be unique according to the dictionary's equality comparer

When adding data simply use Dictionary.ContainsKey Method which would return a Boolean value to indicate Key existence.

ContainsKey Method :

Determines whether the Dictionary contains the specified key.

Hope you would go thorough documents and fulfill the requirement.

Additional: for sorting ,, using LINQ would be easy (Source)

// dictionary is our Dictionary<int,int>
var items = from pair in dictionary orderby pair.Value ascending select pair; 

// Display results.
 foreach (KeyValuePair<string, int> pair in items)
 { 
      Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
 } 

Upvotes: 1

CodingDefined
CodingDefined

Reputation: 2142

Is there a reason you're not using Dictionary?

For using normal List and KeyValuePair you can use the below code

//inside a function

foreach (KeyValuePair<int, int> kvp in myList)  
   if (kvp.Key == key)  
        return;  
myList.Add(new KeyValuePair<int, int>(key, value));  

EDIT : When using Dictionary you can use the below code

var items = from pair in dictionary
            orderby pair.Value ascending
            select pair;

Upvotes: 0

Related Questions