Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding already existing value in Key Value pair

Tags:

c#

.net

key-value

I am storing a string and int value in Key value pair.

var list = new List<KeyValuePair<string, int>>();

While adding i need to check if string(Key) already exists in list, if exists i need to add it to Value instead of adding new key.
How to check and add?

like image 819
Olivarsham Avatar asked Jan 23 '13 05:01

Olivarsham


People also ask

How do you check if a key-value pair exists in a list C#?

You can use IEqualityComparer<KeyValuePair<string, int>> .

Can key-value pair have duplicate keys?

You can use List<KeyValuePair<string,int>> . This will store a list of KeyValuePair 's that can be duplicate.

What are presented in key value pairs?

A key-value pair consists of two related data elements: A key, which is a constant that defines the data set (e.g., gender, color, price), and a value, which is a variable that belongs to the set (e.g., male/female, green, 100).

What is a key value pair?

A key value pair is essentially a set of two data items – a key and a value. The value corresponds to the key, with the key being marked as the unique identifier. Multiple key value pairs together make up a key value database.

Why is my KeyValuePair not returning a single value?

Besides that you are grouping on the value, not on the key, there is something else wrong: you expect a single value, while the grouped result has multiple values. Without joining them, you can't return an enumerable of KeyValuePair<string, string>. If you just want to have any value, use First():

What is a key-value pair extractor?

This tutorial blog examines some of the use cases of key-value pair extractions, the traditional and current approaches to solve the task, and a sample implementation with code. Key-Value Pairs or KVPs are essentially two linked data items, a key, and a value, where the key is used as a unique identifier for the value.

How to create local database using key-value pair information of record?

There are some steps involve in creating the local database and fetch records from it using key-value pair information of record. These steps are as follows: Create package.json file in the root of the project directory using the following command: Install express and body-parser package using the following command:


6 Answers

Instead of List you can use Dictionary and check if it contains key then add the new value to the existing key

int newValue = 10;
Dictionary<string, int> dictionary = new Dictionary<string, int>();
if (dictionary.ContainsKey("key"))
    dictionary["key"] = dictionary["key"] + newValue;
like image 90
Habib Avatar answered Oct 21 '22 13:10

Habib


use dictonary. Dictionary in C# and I suggest you to read this post Dictonary in .net

Dictionary<string, int> dictionary =
        new Dictionary<string, int>();
    dictionary.Add("cat", 2);
    dictionary.Add("dog", 1);
    dictionary.Add("llama", 0);
    dictionary.Add("iguana", -1);

to check. use ContainsKey ContainsKey

if (dictionary.ContainsKey("key"))
    dictionary["key"] = dictionary["key"] + yourValue;
like image 21
Ravi Gadag Avatar answered Oct 21 '22 13:10

Ravi Gadag


If you need use the list,you must foreach the list,and look for the keys. Simplely,you can use hashtable.

like image 38
Jhonny Avatar answered Oct 21 '22 13:10

Jhonny


Your needs exactly describe the design of Dictionarys?

Dictionary<string, string> openWith = 
        new Dictionary<string, string>();

// Add some elements to the dictionary. There are no  
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");

// If a key does not exist, setting the indexer for that key 
// adds a new key/value pair.
openWith["doc"] = "winword.exe";
like image 22
Karthik T Avatar answered Oct 21 '22 12:10

Karthik T


For sure, dictionary is preferable in your case. You can not modify the Value of KeyValue<string,int> class as it is Immutable.

But even if you still want to use List<KeyValuePair<string, int>>();. You can use IEqualityComparer<KeyValuePair<string, int>>. Code will be like.

public class KeyComparer : IEqualityComparer<KeyValuePair<string, int>>
{

    public bool Equals(KeyValuePair<string, int> x, KeyValuePair<string, int> y)
    {
        return x.Key.Equals(y.Key);
    }

    public int GetHashCode(KeyValuePair<string, int> obj)
    {
        return obj.Key.GetHashCode();
    }
}

And use it in Contains like

var list = new List<KeyValuePair<string, int>>();
        string checkKey = "my string";
        if (list.Contains(new KeyValuePair<string, int>(checkKey, int.MinValue), new KeyComparer()))
        {
            KeyValuePair<string, int> item = list.Find((lItem) => lItem.Key.Equals(checkKey));
            list.Remove(item);
            list.Add(new KeyValuePair<string, int>("checkKey", int.MinValue));// add new value
        }

which does not sounds good way.

hope this info helps..

like image 31
D J Avatar answered Oct 21 '22 13:10

D J


For anyone who has to use a List (which was the case for me, since it does things Dictionary doesn't), you can just use a lambda expression to see if the List contains the Key:

list.Any(l => l.Key == checkForKey);
like image 40
WATYF Avatar answered Oct 21 '22 13:10

WATYF