Return Value on Dictionary - c#

It is such that I must return the key parts that add no value.
key states that I've written but I would like to have out of this one return is just VALUE.
I've looked at ContainsKey who are here on this page.
http://www.dotnetperls.com/dictionary
the way I put "PakkeidUnik" into the metadata field you can see here: https://stackoverflow.com/a/37605865/6115825
I therefore get hold of Value as you can see here:
return stripeCustomer.Metadata = new Dictionary<string, string>()
{
Dictionary["PakkeidUnik"];//HERE ARE ITS ERROR!
};
My error are here:
UPDATE

It's a bit unclear what you're asking, you but seem to say you want to get the value for that key (having already set the values per your other question).
You simply use the indexer and pass the key:
return stripeCustomer.Metadata["PakkeidUnik"]
How to use a dictionary is covered in the article you've found. You also might find the examples in the documentation useful.

You seem to be confusing the dictionary initiator syntax, and the syntax for reading the value from a dictionary based on a known key.
A dictionary can be initialised with values like this:
var dict = new Dictionary<string,string>()
{
{"Key1","Value1"},
{"Key2","Value2"}
}
If you then want to read one of the values by key you use this:
var value = dict["Key1"]; // value will contain "Value1"

See the code below:
stripeCustomer.Metadata = new Dictionary<string, string>()
{
{ "PakkeidUnik", "The Value You would like to return for key PakkeidUnik" }
};
return stripeCustomer.Metadata;

Related

C# Dictionary filtering (LINQ) values and getting the key

I have a dictionary fooDictionary<string, MyObject>.
I am filtering the fooDictionary to get only the MyObject with a specific value of the property.
//(Extension method is a extension method that I made for the lists
//(PS: ExtensionMethod returns only 1x MyObject))
fooDictionary.Values.Where(x=>x.Boo==false).ToList().ExtensionMethod();
But I also want to get the keys of the already filtered MyObject's. How can I do that?
Instead of just pulling the values, query the KeyValuePair
fooDictionary.Where(x => !x.Value.Boo).ToList();
This will give you all the key value pairs where the MyObject has a Boo value of false.
Note: I changed your line x.Value.Boo == false to !x.Value.Boo as that is the more common syntax and is (IMHO) easier to read/understand the intent.
EDIT
Based on you updating the question to change from dealing with a list to this new ExtensionMethod here is an updated answer (I am leaving the rest as is as it answers what the original posted question was).
// Note this is assuming you can use the new ValueTuples, if not
// then you can change the return to Tuple<string, MyObject>
public static (string key, MyObject myObject) ExtensionMethod(this IEnumerable<KeyValuePair<string, MyObject>> items)
{
// Do whatever it was you were doing here in the original code
// except now you are operating on KeyValuePair objects which give
// you both the object and the key
foreach(var pair in items)
{
if ( YourCondition ) return (pair.Key, pair.Value);
}
}
And use it like this
(string key, MyObject myObject) = fooDictionary.Where(x => !x.Value.Boo).ExtensionMethod();

How to access value in a Dictionary that has a Tuple as the Key in c#?

I have created a dictionary with Tuples as keys and a enumerator as value.
mKeyValue.Add(Tuple.Create(lineCount,columnID),(E)style);
mKeyValue is the dictionary.
static Dictionary<Tuple<int,int>,E> mKeyValue = new Dictionary<Tuple<int,int>,E>();
Now how to access elements in this dictionary?
I used something like this,
mKeyValue[Tuple<lineCount,columnID>];
but it doesn't work.
It's no different than usage with any other type of key. You need to pass an instance of the type, not the type (declaration) itself to the indexer.
You wouldn't say myKeyValue[int], for a Dictionary<int, ...>, when you really wanted myKeyValue[5]. Just the the key looks a little more "complicated" in this case.
Example:
// Lookup entry for LineCount = 1, ColumnID = 4711
var value = myKeyValue[Tuple.Create(1, 4711)];
Basically, just like you did when adding an entry with Dictionary<>.Add(...).
If you already have a Tuple<int,int> defined then use that as key like mKeyValue[t];
Tuple<int,int> t = Tuple.Create(1, 1);
mKeyValue.Add(Tuple.Create(1, 1), (E)21);
var data = mKeyValue[t];

How to handle data from nested dictionary in C#

Im have setup a nested Dictionary as follows:
static Dictionary<string, Dictionary<UInt32, TClassType> > m_dictionary = new Dictionary<string, Dictionary<UInt32, TClassType>>();
The "TClassType" contains three attributes:
Title (string)
code (uint)
Address (string)
I add value to this nested structure as follows:
TClassType newEntry = new TClassType(s_title, ui_code, s_address)
if (! m_dictionary.ContainsKey(s_title))// check as the same s_title can occur multiple times but have different ui_code and s_address values
{
m_dictionary.Add(s_title, new Dictionary<uint, TClassType>());
}
m_dictionary[s_title].Add(ui_code, s_address);
Now my question is what is a good way to access all of the values for a specific key [s_title]?
the key [s_title] will contain many items within the nested Dictionary, and for a unique [s_title] entry I would like to obtain all of the relevant keys and values related to this outter key from within the nested Dictionary.
Sorry I hope that's not confusing, I find it as hard to ask as I do trying to implement.
Thank you all in advance
Try this:
if (m_dictionary.Contains(s_title))
foreach(TClassType entry in m_dictionary[s_title].Values)
// Do something with the entry.
Have you used linq before? This would be a prime usage for groupby. What you're doing adds a level of convolution.
With your current setup if you have a list of TClassType you would be able to use the linq where expression to grab only those with the title you are looking for and then the ui_code you need.
Edit for example (I was on mobile before which is hard to code on :))
IEnumerable<TClassType> entries = entriesList;//whatever you use to populate the entries
var titles = entries.Where(x=> x.s_title == "Title you're looking for").Distinct();

Remove a single value from a NameValueCollection

My data source could have duplicate keys with values.
typeA : 1
typeB : 2
typeA : 11
I chose to use NameValueCollection as it enables entering duplicate keys.
I want to remove specific key\value pair from the collection, but NameValueCollection.Remove(key) removes all values associated with the specified key.
Is there a way to remove single key\value pair from a NameValueCollection,
OR
Is there a better collection in C# that fits my data
[EDIT 1]
First, thanks for all the answers :)
I think I should have mentioned that my data source is XML.
I used System.Xml.Linq.XDocument to query for type and also it was handy to remove a particular value.
Now, my question is, for large size data, is using XDocument a good choice considering the performance?
If not what are other alternatives (maybe back to NameValueCollection and using one of the techniques mentioned to remove data)
The idea of storing multiple values with the same key is somehow strange. But I think you can retrieve all values using GetValues then remove the one you don't need and put them back using Set and then subsequent Add methods. You can make a separate extension method method for this.
NameValueCollection doesn't really allow to have multiple entries with the same key. It merely concatenates the new values of existing keys into a comma separated list of values (see NameValueCollection.Add.
So there really is just a single value per key. You could conceivably get the value split them on ',' and remove the offending value.
Edit: #ElDog is correct, there is a GetValues method which does this for you so no need to split.
A better option I think would be to use Dictionary<string, IList<int>> or Dictionary<string, ISet<int>> to store the values as discrete erm, values
You may convert it to Hashtable
var x = new NameValueCollection();
x.Add("a", "1");
x.Add("b", "2");
x.Add("a", "1");
var y = x.AllKeys.ToDictionary(k => k, k=>x[k]);
make your own method, it works for me --
public static void Remove<TKey,TValue>(
this List<KeyValuePair<TKey,TValue>> list,
TKey key,
TValue value) {
return list.Remove(new KeyValuePair<TKey,TValue>(key,value));
}
then call it on list as --
list.Remove(key,value); //Pass the key value...
Perhaps not the best way, but....
public class SingleType
{
public string Name;
public int Value;
}
List<SingleType> typeList = new List<SingleType>();
typeList.Add (new SingleType { Name = "TypeA", Value = 1 });
typeList.Add (new SingleType { Name = "TypeA", Value = 3 });
typeList.Remove (typeList.Where (t => t.Name == "TypeA" && t.Value == 1).Single());
You can use the Dictionary collection instead:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("typeA", 1);
dictionary.Add("typeB", 1);
When you try to insert type: 11 it will throw exception as Key already exists. So you can enter a new key to insert this data.
Refer this Tutorial for further help.

Add to Dictionary<string, string> using foreach

what is the best way to ensure that optionValue is always unique in the following scenario?
public Dictionary<string, string> Dict = new Dictionary<string, string>();
foreach (string optionKey in i.options.Keys)
{
string optionValue = i.options.Values.ToString();
Dict.Add(optionKey, optionValue);
}
EDIT: i.options contains a key and a value pair. I need to ensure that for each key the corresponding value is added to the dictionary
EDIT2: corrected order of Dict.Add(optionKey, optionValue)
Just test for it:
if(!Dict.ContainsKey(optionValue))
Dict.Add(optionValue, optionKey)
Based on your variable names it looks like you have key and value reversed though, if optionKey is your lookup key it should be:
Dict.Add(optionKey, optionValue);
A cursory browsing of the MSDN documentation reveals that you can use the obvious method ContainsKey(string) to check to see if a dictionary contains a certain key.
In a Dictionary all keys are unique. If you want to prevent an exception when adding entries to the Dictionary, use
if (!Dict.ContainsKey(optionKey)) {
Dict.Add(optionKey, optionValue);
} else {
Debug.Print("Key '"+optionKey+"' already exists");
}
Depends how you want to handle duplicates.
E.g "last one wins"
foreach(...)
{
// Will overwrite an existing key
Dict[optionValue] = optionKey;
}
"First one wins":
foreach(...)
{
if (!Dict.ContainsKey(optionValue)) Dict.Add(optionValue, optionKey);
}
public Dictionary<string, string> Dict = new Dictionary<string, string>();
foreach (string optionKey in i.options.Keys)
{
string optionValue = i.options.Values.ToString();
if(!Dict.ContainsValue(optionValue))
Dict.Add(optionValue, optionKey);
}
See
http://msdn.microsoft.com/en-us/library/kw5aaea4(v=vs.100).aspx
If you are just worried about exceptions, then just use the item property:
Dict[optionValue] = optionKey;
MSDN: If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key.
Or if you really want to do the check, use the ContainsKey method to check
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
Other folks have been suggesting that you simply test to see if the key exists, and skip adding if it does. However, this may lead to lost data. You should create a custom class or type and use that with your dictionary like so:
public Dictionary< Guid, CustomObjectOrType > Dict = new
Dictionary< Guid, CustomObjectOrType >();
This way you can ensure that each key is unique (a Guid) while preserving all option values and option keys.

Categories

Resources