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.
Related
I'm new to a programming with c#. How to extract IEnumarable key value pair from dictionary that has type <string, IEnumarable<KeyValuePair<string, string>>> to another dictionary<string, string>? Preferebly using linq. Thank you in advance.
Obviously KvpValues dictionary has some values in it. It's just a pseudo code for present what i have.
Trying to do something like that:
Dictionary<string, IEnumarable<KeyValuePair<string, string>>> KvpValues = new Dictionary<string, IEnumarable<KeyValuePair<string, string>>>();
Dictionary<string,string> values = KvpValues.Values.ForEach(k=>k.Key, v=>v.Value);
It seems like what you want to do is flatten the Values from the original Dictionary into a new Dictionary. Assuming there will be no key conflicts, your code is close, you just need to convert your IEnumerable<IEnumerable<KeyValuePair>> into a IEnumerable<KeyValuePair> which is what Enumerable.SelectMany does for you:
Dictionary<string,string> values = KvpValues.Values.SelectMany(kvs => kvs).ToDictionary(k => k.Key, v => v.Value);
I have two dictionaries:
Dictionary<string, Tuple<T, T>> dict1
Dictionary<Enum, Tuple<string, DateTime, DateTime>> dict2
The string value in the first item in the tuple is sometimes equal to the key in the first dictionary. I would like to sort the second dictionary by the enum value and then sort the first dictionary based on the order that dict2 has. How would I be able to do that while retaining the other keys that might be in dict1? I'm able to get as far as sorting the dictionary.
var positions = new Dictionary<Enum, string>();
//This foreach loop can be simplified by a linq expression.
foreach (var position in dict2)
{
var isFound = dict1.Any(x => x.Key == position.Value.Item1.Value);
if (isFound)
{
clubPositions.Add(position.Key, position.Value.Item1.Value);
}
}
var sortedPositions = positions.OrderByDescending(x => x.Key);
You are looking for the SortedDictionary documented on MSDN here. You will need to instantiate them as such:
var dict1 = new SortedDictionary<string, Tuple<DateTime, DateTime>>();
var dict2 = new SortedDictionary<Enum, Tuple<string, DateTime, DateTime>>();
Once you have the sorted dictionaries instances you can use LINQ to map or filter or do whatever else is desired on them. When items are added to the dictionaries they are automatically sorted based on either the ICompare<T> for the given TKey (or the default IComparer if not explicitly provided).
One downside is the fact that this sorts based on the key alone, there is no concept of sorting based on values.
The way I understand the question is not to sort the first dictionary, but to be able to iterate its elements in order defined by the second dictionary keys. If that's correct, the following should do the trick:
var orderedKeys = new HashSet<string>(dict2.OrderBy(e => e.Key).Select(e => e.Value.Item1));
var orderedEntries = orderedKeys.Where(dict1.ContainsKey)
.Select(key => new KeyValuePair<string, Tuple<T, T>>(key, dict1[key]))
.Concat(dict1.Where(e => !orderedKeys.Contains(e.Key)));
Note that it will put the entries that has no corresponding key last in the order.
You can not sort dictionary as it uses hash algorithm for constant search.
A regular dictionary cannot be sorted. You could use a SortedDictionary, it exists for this exact purpose.
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..
I see many question/answers about how to convert a Hashtable to a Dictionary, but how can I convert a Dictionary to a Hashtable?
The easiest way is using constructor of Hashtable:
var dictionary = new Dictionary<object, object>();
//... fill the dictionary
var hashtable = new Hashtable(dictionary);
Dictionary<int, string> dictionary = new Dictionary<int, string>
{
{1,"One"},
{2,"Two"}
};
Hashtable hashtable = new Hashtable(dictionary);
Try this
Seems pretty rare to want to do, but at the simplest:
var hash = new Hashtable();
foreach(var pair in dictionary) {
hash.Add(pair.Key,pair.Value);
}
(assuming no unusual "implements typed equality check but not untyped equality check" etc)
You might want to consider using the Hashtable constructor overload that takes an IEqualityComparer parameter:
var hashtable = new Hashtable(dictionary, (IEqualityComparer) dictionary.Comparer);
In this way, your Hashtable uses the same Comparer as the dictionary. For example, if your dictionary used a case-insensitive string key, you might want your Hashtable to be case-insensitive too. E.g.:
var d = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
d.Add("a", "a");
d.Add("b", "b");
bool found;
found = d.ContainsKey("A"); // true
var hashtable1 = new Hashtable(d);
var hashtable2 = new Hashtable(d, (IEqualityComparer) d.Comparer);
found = hashtable1["A"] != null; // false - by default it's case-sensitive
found = hashtable2["A"] != null; // true - uses same comparer as the original dictionary
Suppose I have an array of strings like :
myArray["hello", "my", "name", "is", "marco"]
to access to this variable, I have to put an integer as index. So if I wanto to extract the third element I just do :
myArray[2]
Now, I'd like to use label instead of integer.
So for example somethings like :
myArray["canada"]="hello";
myArray["america"]="my";
myArray["brazil"]="name";
myArray["gosaldo"]="is";
myArray["italy"]="marco";
How can I do this on C#? Is it possible? Thanks
That's called an associative array, and C# doesn't support them directly. However, you can achieve exactly the same the effect with a Dictionary<TKey, TValue>. You can add values with the Add method (which will throw an exception if you try to add an already existing key), or with the indexer directly, as below (this will overwrite the existing value if you use the same key twice).
Dictionary<string, string> dict = new Dictionary<string, string>();
dict["canada"] = "hello";
dict["america"] = "my";
dict["brazil"] = "name";
dict["gosaldo"] = "is";
dict["italy"] = "marco";
C# has a Dictionary class (and interface) to deal with this sort of storage. For example:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("canada", "hello");
dict.Add("america", "my");
dict.Add("brazil", "name");
dict.Add("gosaldo", "is");
Here are the docs: http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
With a Dictionary you will be able to set the "key" for each item as a string, and and give them string "values". For example:
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("canada", "hello");
You're looking for an associative array and I think this question is what you're looking for.