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?
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;
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;
If you need use the list,you must foreach the list,and look for the keys.
Simplely,you can use hashtable.
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);
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";
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..
Related
I have list declared as
List<KeyValuePair<string, Int64>> KPList = new List<KeyValuePair<string, long>>();
I need to check if a combination of key and value already exists. I can't use dictionary since I need to have unique combination of key and value where in case a key will have multiple values but as a single pair
if(!KPList.Any(p=> p.Key ==keyp && p.Value == valuep))
What is wrong in this?
You can also use HashSet, which doesn't have values, but works as you need.
HashSet< Tuple<string, long> > KPSet = new HashSet< Tuple<string, long> >();
...
if(KPSet.Contains(p))
{
...
}
For easy-use and best performance I would like to suggest use combination of Dictionary and HashSet :
var KPDict = new Dictionary<string, HashSet<long>>();
Then it will provides you O(1)+O(1) lookup complexity and easy check of value:
if (KPDict.ContainsKey(keyp) && KPDict[keyp].Contains(valuep)) {
//do some actions
}
else{
//some logic in case keyp, valuep pair not found in KPDict
}
I have some lines from text files that i want to add into the Dictionary.I am using Dictionary for the first time.While adding up starting lines it was Ok but suddenly i got error:
An item with the same key has already been added
Here in my code there are duplicate keys which i can not change.Here is my code in c#
Dictionary<string, string> previousLines = new Dictionary<string, string> { };
previousLines.Add(dialedno, line);
Here dialedno is the key and line is the textfile line.
Here is the code from which i am retrieving the given line based on key.
string tansferOrginExt = previousLines[dialedno];
So my concern is how to allow to add duplicate keys in Dictionary if possible and if not how can i get similar functionality.
how to allow to add duplicate keys in Dictionary
It is not possible. All keys should be unique. As Dictionary<TKey, TValue> implemented:
Every key in aDictionary<TKey, TValue> must be unique according to
the dictionary's equality comparer.
Possible solutions - you can keep collection of strings as value (i.e. use Dictionary<string, List<string>>), or (better) you can use Lookup<TKey, TValue> instead of dictionary.
how to check for duplicate keys and delete previous value from
Dictionary?
You can check if the key exists with previousLines.ContainsKey(dialedno) but if you always want to hold the last line, then just replace whatever dictionary had for the key, or add the new key if it is not in the dictionary:
previousLines[dialedno] = line;
We can Use a List of Key Value Pair
List<KeyValuePair<string, string>> myduplicateLovingDictionary= new List<KeyValuePair<string, string>>();
KeyValuePair<string,string> myItem = new KeyValuePair<string,string>(dialedno, line);
myduplicateLovingDictionary.Add(myItem);
Its not possible to add duplicate items to a Dictionary - an alternative is to use the Lookup class.
Enumerable.ToLookup Method
Creates a generic Lookup from an IEnumerable.
Example:
class Program
{
private static List<KeyValuePair<string, int>> d = new List<KeyValuePair<string, int>>();
static void Main(string[] args)
{
d.Add(new KeyValuePair<string, int>("joe", 100));
d.Add(new KeyValuePair<string, int>("joe", 200));
d.Add(new KeyValuePair<string, int>("jim", 100));
var result = d.Where(x => x.Key == "joe");
foreach(var q in result)
Console.WriteLine(q.Value );
Console.ReadLine();
}
}
List< KeyValuePair < string, string>> listKeyValPair= new List< KeyValuePair< string, string>>();
KeyValuePair< string, string> keyValue= new KeyValuePair< string, string>("KEY1", "VALUE1");
listKeyValPair.Add(keyValue);
If your question is if you can add the same key twice, the answer is No.
However if you want to just iterate through the item and then increase the count of the value for the particular Key, you can achieve that by using "TryAdd" method.
var dict = new Dictionary<int, int>();
foreach (var item in array)
{
dict.TryAdd(item, 0);
dict[item]++;
}
The same thing we are trying to achieve with if else, can be achieved with this method.``
https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2.tryadd?view=netframework-4.7.2
I need a two column list like:
List<int,string> mylist= new List<int,string>();
it says
using the generic type System.collection.generic.List<T> requires 1 type arguments.
Depending on your needs, you have a few options here.
If you don't need to do key/value lookups and want to stick with a List<>, you can make use of Tuple<int, string>:
List<Tuple<int, string>> mylist = new List<Tuple<int, string>>();
// add an item
mylist.Add(new Tuple<int, string>(someInt, someString));
If you do want key/value lookups, you could move towards a Dictionary<int, string>:
Dictionary<int, string> mydict = new Dictionary<int, string>();
// add an item
mydict.Add(someInt, someString);
You could use an immutable struct
public struct Data
{
public Data(int intValue, string strValue)
{
IntegerData = intValue;
StringData = strValue;
}
public int IntegerData { get; private set; }
public string StringData { get; private set; }
}
var list = new List<Data>();
Or a KeyValuePair<int, string>
using Data = System.Collections.Generic.KeyValuePair<int, string>
...
var list = new List<Data>();
list.Add(new Data(12345, "56789"));
With the new ValueTuple from C# 7 (VS 2017 and above), there is a new solution:
List<(int,string)> mylist= new List<(int,string)>();
Which creates a list of ValueTuple type. If you're targeting .NET Framework 4.7+ or .NET/.NET Core, it's native, otherwise you have to get the ValueTuple package from nuget.
It's a struct opposing to Tuple, which is a class. It also has the advantage over the Tuple class that you could create a named tuple, like this:
var mylist = new List<(int myInt, string myString)>();
That way you can access like mylist[0].myInt and mylist[0].myString
Since your example uses a generic List, I assume you don't need an index or unique constraint on your data. A List may contain duplicate values. If you want to insure a unique key, consider using a Dictionary<TKey, TValue>().
var list = new List<Tuple<int,string>>();
list.Add(Tuple.Create(1, "Andy"));
list.Add(Tuple.Create(1, "John"));
list.Add(Tuple.Create(3, "Sally"));
foreach (var item in list)
{
Console.WriteLine(item.Item1.ToString());
Console.WriteLine(item.Item2);
}
Use C# Dictionary datastructure it good for you...
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("one", 1);
dict.Add("two", 2);
You can retrieve data from Ditionary in a simple way..
foreach (KeyValuePair<string, int> pair in dict)
{
MessageBox.Show(pair.Key.ToString ()+ " - " + pair.Value.ToString () );
}
For more example using C# Dictionary... C# Dictionary
Navi.
Not sure about your specific scenario, but you have three options:
1.) use Dictionary<..,..>
2.) create a wrapper class around your values and then you can use List
3.) use Tuple
List<Tuple<string, DateTime, string>> mylist = new List<Tuple<string, DateTime,string>>();
mylist.Add(new Tuple<string, DateTime, string>(Datei_Info.Dateiname, Datei_Info.Datum, Datei_Info.Größe));
for (int i = 0; i < mylist.Count; i++)
{
Console.WriteLine(mylist[i]);
}
For that, you could use a Dictionary where the int is the key.
new Dictionary<int, string>();
If you really want to use a list, it could be a List<Tuple<int,string>>() but, Tuple class is readonly, so you have to recreate the instance to modifie it.
how to add duplicate keys to dictionary
i.e i have already added the key,value pair as rollno,1
but i need to add the same parameter to the dictionary,but it is not allowing to add. how to add duplicated keys/repeated key in dictionary
.
or any other choice..
any idea???
That doesn't make sense, if you added duplicate keys to the dictionary, how would it be able to find which one you want when you look them up?
Possibly you're looking for something like a List< KeyValuePair < T, T > >? Where you could store a list of pairs rather than an actual dictionary.
Check out this:
What is the point of Lookup<TKey, TElement>?
You can use the Lookup class to help you create collections with duplicates keys.
I think it should work in your case
class Program
{
private static List<KeyValuePair<string, int>> d = new List<KeyValuePair<string, int>>();
static void Main(string[] args)
{
d.Add(new KeyValuePair<string, int>("rollno", 1));
d.Add(new KeyValuePair<string, int>("rollno", 2));
d.Add(new KeyValuePair<string, int>("rollno", 3));
var result = d.Where(x => x.Key == "joe");
foreach(var q in result)
Console.WriteLine(q.Value );
Console.ReadLine();
}
}
Dictionary<string, string> optionDictionary = new Dictionary<string, string>();
optionDictionary = ....;
SortedDictionary<string, string> optionsSorted;
if(sorting)
{
optionsSorted = new SortedDictionary<string, string>(optionDictionary );
// Convert SortedDictionary into Dictionary
}
return optionDictionary ;
You can pass in your optionsSorted<TKey,TValue> dictionary as a parameter to an instance of a new Dictionary<TKey,TValue>, Like so:
var dictionary = new Dictionary<type1,type2>(optionsSorted);
Try the following
var dictionary = optionsSorted.ToDictionary(x => x.Key, x=> x.Value);
It is not entirely clear to me what you are trying to accomplish. I am assuming that you have a function that returns a Dictionary and you want it to be a sorted dictionary when sorting is true.
If that is true, then you need a return type that can be a Dictionary or a SortedDictionary.
If you want a single function doing that, I would use IDictionay as return type of the method.
Just use the ToDictionary method.