C# Comparaison between Dictionary<string, int> and value in enter - c#

I have a function for stock many string associate to int:
public int Scale(string value)
{
this.stringToInt = new Dictionary<string, int>()
{
{"1p",00},{"2p",01},{"3p",03} ... {"300p",40}
};
// Here i try to do something like that: if(value == (String in dictionary) return associate int
}
So i try to do a comparaison between string receive in enter and string in my dictionary for return associate int.
Any idea?
Thanks you for help !

You can use ContainsKey() method of Dictionary to check if the key is present in dictionary:
if (this.stringToInt.ContainsKey(value)
{
return this.stringToInt[value];
}
else
{
// return something else
}
Another way is to use TryGetValue():
var valueGot = this.stringToInt.TryGetValue(value, out var associate);
if (valueGot)
{
return associate;
}
else
{
// return something else
}

Related

Custom OAuth in Unity linking to Parse Server

I am using Unity with Parse Server and now wants to be able to link a user with OAuth.
This is what I am trying so far, but with no luck.
[System.Serializable]
public class DGUOAuth
{
public string dguId = "";
public string access_token = "";
}
DGUOAuth auth = new DGUOAuth()
{
access_token = "F12w06Ddqx1k5qj75JQWRZmzh16Zgf05wHExNnHAnh8",
dguId = "25-1999"
};
System.Threading.CancellationToken canceltoken;
Dictionary<string, object> data = new Dictionary<string, object>();
data.Add("authData", auth);
Debug.Log("Ready for linking the user!");
DataManager.user.LinkWithAsync("DGU", data, canceltoken).ContinueWith(t =>
{
if (t.IsFaulted)
{
Debug.Log("Faulted: " + t.Exception);
// Errors from Parse Cloud and network interactions
using (IEnumerator<Exception> enumerator = t.Exception.InnerExceptions.GetEnumerator())
{
if (enumerator.MoveNext())
{
ParseException error = (ParseException)enumerator.Current;
Debug.Log(error.Message);
// error.Message will contain an error message
// error.Code will return "OtherCause"
}
}
}
else
{
Debug.Log("User is linked");
}
});
Nothing happens and I only get "Ready for linking the user!" but no logs after that?! The documentation for LinkWithAsync and Unity is almost not existing...
Really hope someone can help me on this. Any help is appreciated and thanks in advance :-)
----- EDIT -----
Now, added a Debug.Log just after t.isFaulted and get this log:
System.AggregateException: One or more errors occurred. ---> System.ArgumentException: Unable to encode objects of type DGUOAuth
Not sure how to solve this. I do not get any error logs in the Parse server logs.
Issue
The error is basically coming from JsonUtility.Encode
public static string Encode(IDictionary<string, object> dict)
{
if (dict == null)
throw new ArgumentNullException();
if (dict.Count == 0)
return "{}";
StringBuilder builder = new StringBuilder("{");
foreach (KeyValuePair<string, object> pair in dict)
{
builder.Append(Encode(pair.Key));
builder.Append(":");
builder.Append(Encode(pair.Value));
builder.Append(",");
}
builder[builder.Length - 1] = '}';
return builder.ToString();
}
where builder.Append(Encode(pair.Value)); then tries to call Encode(object)
public static string Encode(object obj)
{
if (obj is IDictionary<string, object> dict)
return Encode(dict);
if (obj is IList<object> list)
return Encode(list);
if (obj is string str)
{
str = escapePattern.Replace(str, m =>
{
switch (m.Value[0])
{
case '\\':
return "\\\\";
case '\"':
return "\\\"";
case '\b':
return "\\b";
case '\f':
return "\\f";
case '\n':
return "\\n";
case '\r':
return "\\r";
case '\t':
return "\\t";
default:
return "\\u" + ((ushort) m.Value[0]).ToString("x4");
}
});
return "\"" + str + "\"";
}
if (obj is null)
return "null";
if (obj is bool)
return (bool) obj ? "true" : "false";
if (!obj.GetType().GetTypeInfo().IsPrimitive)
throw new ArgumentException("Unable to encode objects of type " + obj.GetType());
return Convert.ToString(obj, CultureInfo.InvariantCulture);
}
so without knowing that thing at all it looks like it simply expects an IDictionary<string, object> where the value can only be of the types
IDictionary<string, object> (where the value type again underlies the same type restrictions)
IList<object> (where the element type again underlies the same restrictions)
string
bool
primitive types (int, short, ulong, float, etc)
your given class DGUOAuth is neither of these => ArgumentException.
Solution(s)
So I would simply not use your DGUOAuth class at all but simply construct according dictionary either directly as
var data = new Dictionary<string, object>
{
{"authData" , "{\"access_token\" : \"F12w06Ddqx1k5qj75JQWRZmzh16Zgf05wHExNnHAnh8\", \"dguId\" : \"25-1999\"}"}
};
or if you want to as
var data = new Dictionary<string, object>
{
{"authData" , new Dictionary<string, object>
{
{"access_token", "F12w06Ddqx1k5qj75JQWRZmzh16Zgf05wHExNnHAnh8"},
{"dguId", "25-1999"}
}
}
};
where of course you can fill in the values also dynamically from variables if needed.
The alternative would be to make sure that your DGUOAuth returns such a dictionary this makes it maybe easier for you if you need to pass this around a lot or configure it via the Inspector
[System.Serializable]
public class DGUOAuth
{
public string dguId = "";
public string access_token = "";
public DGUOauth(string id, string token)
{
dguId = id;
access_token = token;
}
public IDictionary<string, object> ToDictionary()
{
return new Dictionary<string, object>
{
{"access_token", access_token},
{"dguId", dguId}
};
}
}
and then use it like
var data = new Dictionary<string, object>
{
{"authData", new DGUOauth("25-1999", "F12w06Ddqx1k5qj75JQWRZmzh16Zgf05wHExNnHAnh8").ToDictionary()}
};
or actually implements according interface IDictionary<string, object> which in my eyes is a lot of overkill for this little task.
I'm not even sure if you need that field name authData there or if it rather simply would expect
var data = new Dictionary<string, object>
{
{"access_token", "F12w06Ddqx1k5qj75JQWRZmzh16Zgf05wHExNnHAnh8"},
{"dguId", "25-1999"}
};
but that's something you will have to try.

How to take dynamic datatype in dictionary object

Hello I came up with situation where I am taking value from user in the form of querystring.
Name of first 2 parameter is fix,so name name of querystring is fix.After these 2 parameter,user may enter or may not enter any parameter.Parameter count can be from 1 to many and vary in datatype.
Ex: sitename/sample.aspx?username=''&userid=''&Date=
Ex: sitename/sample.aspx?username=''&userid=''&Date=&amount=
That's why I created dictionary object and storing key and value of dynamic querystring into it(not username and userid).
Dictionary<string, string> queryStringValues = new Dictionary<string, string>();
foreach (string key in Request.QueryString.AllKeys)
{
queryStringValues.Add(key, Request.QueryString[key]);
}
Here I have created dictionary of <string,string> .But my key must be string and value may not string. It can be int,date .How to take that?
At last I want to check datatype of value? How to do that?
Query string as the name says it's a string ( a collection of key value pair that consists of 2 strings ( key and value ) ) so basically you cannot know for sure if value of Date would be convertible to DateTime object.
You can though make something like factory ( which I've done few months ago ) to pair key with different Type.
To explain this in more detail :
public static class Factory
{
static Dictionary<string, Type> _fac = new Dictionary<string, Type>();
public static void Assign<T>(string key)
{
if(_fac.ContainsKey(key))
{
if(_fac[key] != typeof(T)) _fac[key] = typeof(T);
}
else
{
_fac.Add(key, typeof(T));
}
}
public static object Retrieve(string key, string value)
{
if(_fac.ContainsKey(key))
{
if(_fac[key] == typeof(string))
return value;
TypeConverter converter = TypeDescriptor.GetConverter(_fac[key]);
if(converter.CanConvertFrom(typeof(string))
return converter.ConvertFromString(value);
}
return null;
}
public static Type TypeFor(string key)
{
if(_fac.ContainsKey(key))
return _fac[key];
return null;
}
}
To use this simply do something like :
Factory.Assign<DateTime>("date");
// later on, you can retrieve value using this:
// assume query is "Date=01/01/2001"
Dictionary<string, object> queryStringValues = new Dictionary<string, object>();
foreach (string key in Request.QueryString.AllKeys)
{
queryStringValues.Add(key, Factory.Retrieve(key, Request.QueryString[key]));
}
You could use Dictionary with objects.
Dictionary<string, object> queryStringValues = new Dictionary<string, object>();
Note, after that ou should cast your objects to knwon type , something as:
queryStringValues.Add("2", true);
...
var q = queryStringValues["2"];
if (q is bool)
{
var r = !(bool)q;
}

Dictionary Immutable Issue alternative in C#

Not sure of the best alternative to dictionaries in this scenario - objects or arrays.
I need to change the value of the dictionary(or whatever else) depending on whether the id/key exists, adding to the existing value if the id parsed in does exist, never the key/id - what would be the best alternative?
Code
Dictionary<int, int> total = new Dictionary<int, int>();
// elsewhere in a function...
ArrayManager(total, id, value);
public void ArrayManager(Dictionary<int,int> items, int id, int val)
{
int i = 0;
bool found = false;
foreach(var item in items)
{
if(item.Key == id)
{
item.Value += val; // immutable issue stops this from working
found = true;
break;
}
}
if(found == false)
{ // do something }
}
If you're trying to increment the value identified by a given key:
public void ArrayManager(Dictionary<int,int> items, int id, int val)
{
int currentVal = 0;
if (items.TryGetValue(id, out currentVal))
{
int newVal = currentVal + val;
items[id] = newVal;
// Do something else
}
I believe what you are trying to do is:
if(item.Key == id)
{
items[item.Key]+= val;
}

How can I return key value pair from a function

I am implementing a function in C#.
This is the function in my class.I need to get the values from the function to the form.
public void GetRoles(string strGetRoles)
{
string keyObj;
string valueObj;
var parseTree = JsonConvert.DeserializeObject<JObject>(strGetRoles);
foreach (var prop in parseTree.Properties())
{
dynamic propValue = prop.Value;
if (prop.Name == "roles" && prop.Value.HasValues)
{
foreach (var proval in propValue)
{
keyObj = (string)proval.Name;
valueObj = (string)proval.Value;
}
}
else if (prop.Name == "groups" && prop.Value.HasValues)
{
foreach (var proval in propValue)
{
keyObj = (string)proval.Name;
valueObj = (string)proval.Value;
}
}
}
}
strGetRoles is the response string I get after fetching json api.
the propvalue I get is {"roles": {"3": "Reseller","2": "Admin end user"},"groups": []}
Now I want to call this function and get each value in an object or string array.How to return these key pair values?
Thanks in advance!
You can return KeyValuePair like this:
return new KeyValuePair<string,string>(key,value);
or use Tuple
return Tuple.Create(key,value);
if you have more than one KeyValuePair to return use Dictionary, you can read more about performance differences between Tuple and KeyValuePair here. In short using Tuple is better idea because of it's better performance.
Use Tuple<T1, T2>.
public Tuple<string, string> GetRoles(string strGetRoles)
{
//...
return Tuple.Create(key, value);
}
If you have more than one key-value pair, then return a Dictionary<string, string> instead.

Get dictionary value by key

How can I get the dictionary value by a key on a function?
My function code (and the command I try doesn't work):
static void XML_Array(Dictionary<string, string> Data_Array)
{
String xmlfile = Data_Array.TryGetValue("XML_File", out value);
}
My button code:
private void button2_Click(object sender, EventArgs e)
{
Dictionary<string, string> Data_Array = new Dictionary<string, string>();
Data_Array.Add("XML_File", "Settings.xml");
XML_Array(Data_Array);
}
I want on the XML_Array function the variable to be:
string xmlfile = "Settings.xml":
It's as simple as this:
String xmlfile = Data_Array["XML_File"];
Note that if the dictionary doesn't have a key that equals "XML_File", that code will throw an exception. If you want to check first, you can use TryGetValue like this:
string xmlfile;
if (!Data_Array.TryGetValue("XML_File", out xmlfile)) {
// the key isn't in the dictionary.
return; // or whatever you want to do
}
// xmlfile is now equal to the value
Just use the key name on the dictionary. C# has this:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("UserID", "test");
string userIDFromDictionaryByKey = dict["UserID"];
If you look at the tip suggestion:
That is not how the TryGetValue works. It returns true or false based on whether the key is found or not, and sets its out parameter to the corresponding value if the key is there.
If you want to check if the key is there or not and do something when it's missing, you need something like this:
bool hasValue = Data_Array.TryGetValue("XML_File", out value);
if (hasValue) {
xmlfile = value;
} else {
// do something when the value is not there
}
Dictionary<String, String> d = new Dictionary<String, String>();
d.Add("1", "Mahadev");
d.Add("2", "Mahesh");
Console.WriteLine(d["1"]); // It will print Value of key '1'
static void XML_Array(Dictionary<string, string> Data_Array)
{
String value;
if(Data_Array.TryGetValue("XML_File", out value))
{
// ... Do something here with value ...
}
}
static String findFirstKeyByValue(Dictionary<string, string> Data_Array, String value)
{
if (Data_Array.ContainsValue(value))
{
foreach (String key in Data_Array.Keys)
{
if (Data_Array[key].Equals(value))
return key;
}
}
return null;
}
Here is an example which I use in my source code.
I am getting key and value from Dictionary from element 0 to number of elements in my Dictionary. Then I fill my string[] array which I send as a parameter after in my function which accept only params string[]
Dictionary<string, decimal> listKomPop = addElements();
int xpopCount = listKomPop.Count;
if (xpopCount > 0)
{
string[] xpostoci = new string[xpopCount];
for (int i = 0; i < xpopCount; i++)
{
/* here you have key and value element */
string key = listKomPop.Keys.ElementAt(i);
decimal value = listKomPop[key];
xpostoci[i] = value.ToString();
}
...
This solution works with SortedDictionary also.
Dictionary<int,string> dict = new Dictionary<int,string>{
{1,"item1"},
{2,"item2"},
{3,"item3"},
}
int key = 2 // for example
string result = dict.ContainsKey(key) ? dict[key] : null;
private void button2_Click(object sender, EventArgs e)
{
Dictionary<string, string> Data_Array = new Dictionary<string, string>();
Data_Array.Add("XML_File", "Settings.xml");
XML_Array(Data_Array);
}
static void XML_Array(Dictionary<string, string> Data_Array)
{
String xmlfile = Data_Array["XML_File"];
}
I use a similar method to dasblinkenlight's in a function to return a single key value from a Cookie containing a JSON array loaded into a Dictionary as follows:
/// <summary>
/// Gets a single key Value from a Json filled cookie with 'cookiename','key'
/// </summary>
public static string GetSpecialCookieKeyVal(string _CookieName, string _key)
{
//CALL COOKIE VALUES INTO DICTIONARY
Dictionary<string, string> dictCookie =
JsonConvert.DeserializeObject<Dictionary<string, string>>
(MyCookinator.Get(_CookieName));
string value;
if (dictCookie.TryGetValue( _key, out value))
{
return value;
}
else
{
return "0";
}
}
Where "MyCookinator.Get()" is another simple Cookie function getting an http cookie overall value.
(I posted this on another question and I don't know how to link to that so here it is)
A Dictionary<K,V> extension that works. I have been using it for a long time::
public static bool TryGetKey<K, V>(this IDictionary<K, V> instance, V value, out
K key)
{
foreach (var entry in instance)
{
if (!entry.Value.Equals(value))
{
continue;
}
key = entry.Key;
return true;
}
key = default(K);
return false;
}
And use as :
public static void Main()
{
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{"1", "one"},
{"2", "two"},
{"3", "three"}
};
string value="two";
if (dict.TryGetKey(value, out var returnedKey))
Console.WriteLine($"Found Key {returnedKey}");
else
Console.WriteLine($"No key found for value {value}");
}
if (Data_Array["XML_File"] != "") String xmlfile = Data_Array["XML_File"];

Categories