Is there an C# equivalent to the PHP function `parse_str`? - c#

Is there an C# equivalent to the PHP function parse_str?
I couldn't find anything and wrote my own function but is there something in the C# framework?
public Dictionary<string, string> parse_str(string query) {
Dictionary<string, string> data = new Dictionary<string, string>();
foreach(string set in query.Trim('?').Split('&'))
data.Add(set.Split('=')[0], set.Split('=').Length < 2 ? "" : set.Split('=')[1]);
return data;
}​​​​​​

I think you are looking for HttpUtility.ParseQueryString()

If you're taking it from the browser's query string, you can use Request.QueryString
You can get a list of all the keys: Request.QueryString.Keys
Get a value of a key: Request.QueryString["KeyName"]

Related

How to declare array of strings with string index?

In my code i declared like this :
public string[] s ;
and i need to use this string like this :
s["Matthew"]="Has a dog";
s["John"]="Has a car";
when i use s["Matthew"] an error appears and it says "Cannot implicitly convert 'string' to 'int'" .
How can I make a string array to have string index ?
if i write this in php it works :
array() a;
a["Mathew"]="Is a boy";
I need it to work also in asp.net !
public Dictionary<string, string> s;
MSDN documentation
In C#, you cannot access an array element using, as array index, a string.
For this reason you have that cast error, because the index of an array is, by definition of an array, an integer.
Why don't you use a data structure like a dictionary?
var dict = new Dictionary<string,string>();
dict.Add("John","I am John");
//print the value stored in dictionary using the string key
Console.WriteLine(dict["John"]);
Array works on indexes and indexes are in numbers but you are passing string that's why you are getting error, #Christian suggest you to use Dictionary
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}
};
// retrieve values:
foreach (KeyValuePair<string, string> kvp in dict)
{
string key = kvp.Key;
string val = kvp.Value;
// do something
}

Key Value array in C# put into parameter

Coming from PHP, I have never written C# before and I have encountered something like this in C#:
public string rule(string playerId, string action, params string[] optionalData){
...
}
and in PHP it is like this
public function rule($playerId, $action, $optionalData=array()){
...
}
In PHP I simply fill out the parameter for the $optionalData like this...
myVar->rule("123", "myAction", array('url'=>'review.com');
However in C# I am not sure how to fill the optionalData (params string[] optionalData) parameter as it is a key value parameter (like in the PHP example). My question is how do I create a key value array like the PHP that I created in my example and put into the parameter?
CoolClass cc = new CoolClass();
cc.rule("123", "myAction", ???);
I was searching google and was looking at dictionary and hashmaps etc but I am guessing it is an overkill or it does not work..
Many thanks!
When you were looking at dictionaries, you were definitely looking at the right facility.
If rule() in C# is in your own code, may I recommend changing the signature to:
public string rule(string playerId, string action, IDictionary<string, string> optionalData = new Dictionary<string, string>()){
...
}
What this allows you to do:
Operate on the values in optionalData the way that other C# programmers will expect.
The = new Dictionary<string, string>() part of the suggested method signature make the parameter truly optional. It will not be necessary when calling the method.
You can use IDictionary<T> methods to work with the data. Some syntax you should be somewhat familiar with (consider accessing by key optionalData["someString"].)
However, if rule() is not in your code, you would leave out the optionalData by simply omitting parameters. Examples of valid calls of the original C# method in your question:
rule("Bob", "load")
rule("Bob", "load", "url", "www.example.com") (In this case, optionalData[0].Equals("url", StringComparisonOptions.Ordinal) and optionalData[1].Equals("www.example.com", StringComparisonOptions.Ordinal) is true.
One thing to consider about the original method - keep in mind that rule("Bob", "load", 'url") is a valid call, and you would need to have a run-time check to make sure you had the right number of parameters. Another plus to using a Dictionary<TKey, TValue>. You may even consider writing an adapter method to the original rule(), if you can't change it.
You can use a Dictionary:
Dictionary<string,string[]>
or something like:
Dictionary<int, string[]>
I believe dictionary will work in your case.
You can use Dictionary <key_datatype, value_datatype> .
Example:
Your method definition here :
public string rule(string playerId, string action, Dictionary<string, string> optionalData){
...
}
Method call:
Dictionary<string, string> optionalData = new Dictionary<string, string>();
optionalData.Add("url", "review.com");
cc.rule("123", "myAction", optionalData);
Or
you can use DynamoObject to make it more easier to write:
dynamic optionalData = new ExpandoObject();
//The token after the dynamoObject period will be the key to the assigned value.
optionalData.url = "review.com";
cc.rule("123", "myAction", optionalData);
Your method can get the key-value pairs like this:
public string rule(string playerId, string action, dynamic optionalData)
{
...
foreach (var pair in (IDictionary<string, object>)optionalData)
{
if (group.Key == "url")
{
Console.WriteLine(group.Value);
}
else if (group.Key == "post")
{
Console.WriteLine(group.Value);
}
}
}

C# .NET Generate once a string array which his indexes are string values from a table

I have a table contains the columns Title and Info.
I would like to create an array it's index will be the Title, and actual value of the array in that index is the Info in the same row.
So if I have 3 Rows like that:
Title Info
ABC Hi
DEF Sup
GHI Hello
I would like to ask for StringArray["ABC"], and this will return "Hi".
How can I do that?
Thanks Guy
You want a Dictionary<String, String>, not a string array.
var myStrings = new Dictionary<String, String>();
myStrings.Add("ABC", "Hi");
myStrings.Add("DEF", "Sup");
myStrings.Add("GHI", "Hello");
Console.WriteLine(myStrings["ABC"]);
Arrays can only be indexed with an integer. You would have to use Dictionary<string, string>, or some other type that implements IDictionary<string, string>, or you could implement your own type with a string indexer.
Please refer to Dictionary for that
You can do in this way
Dictionary<string, string> Book = new Dictionary<string, string>();
Book.Add("ABC","Hi");
Book.Add("DEF","Sup");
Book.Add("GHI","Hello");
so on and so forth.
So then when you say
Book["ABC"] it will return Hi
You should use dictionary to implement it.
var table = new Dictionary<string,string>(
{"ABC", "Hi"},
{"DEF", "Sup"},
{"GHI", "Hello"}
);
now you can use it
var info = table["ABC"];
you should be careful an exception will be thrown if you use unexisted key
you can use TryGetValue to avoid this exception
string info;
if(!table.TryGetValue("ABC", out info))
{
info = "default value if required";
}

How to create an array with label and not integer

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.

Best way to convert query string to dictionary in C#

I'm looking for the simplest way of converting a query string from an HTTP GET request into a Dictionary, and back again.
I figure it's easier to carry out various manipulations on the query once it is in dictionary form, but I seem to have a lot of code just to do the conversion. Any recommended ways?
HttpUtility.ParseQueryString() parses query string into a NameValueCollection object, converting the latter to an IDictionary<string, string> is a matter of a simple foreach. This, however, might be unnecessary since NameValueCollection has an indexer, so it behaves pretty much like a dictionary.
Here is how I usually do it
Dictionary<string, string> parameters = HttpContext.Current.Request.QueryString.Keys.Cast<string>()
.ToDictionary(k => k, v => HttpContext.Current.Request.QueryString[v]);
How about HttpUtility.ParseQueryString?
Just add a reference to System.Web.dll
Same as Sean, but with Linq (and a function you can copy and paste):
public static Dictionary<string, string> ParseQueryString(string queryString)
{
var nvc = HttpUtility.ParseQueryString(queryString);
return nvc.AllKeys.ToDictionary(k => k, k => nvc[k]);
}
Also, the question asked how to get it back into a query string:
public static string CreateQueryString(Dictionary<string, string> parameters)
{
return string.Join("&", parameters.Select(kvp =>
string.Format("{0}={1}", kvp.Key, HttpUtility.UrlEncode(kvp.Value))));
}
Just had to do this for a mono compatible solution
Regex.Matches(queryString, "([^?=&]+)(=([^&]*))?").Cast<Match>().ToDictionary(x => x.Groups[1].Value, x => x.Groups[3].Value)
In ASP.NET Core, use ParseQuery.
var query = HttpContext.Request.QueryString.Value;
var queryDictionary = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(query);
I like the brevity of Jon Canning's answer, but in the interest of variety, here is another alternative to his answer, that would also work for restricted environments like Windows Phone 8, that lack the HttpUtility.ParseQueryString() utility:
public static Dictionary<string, string> ParseQueryString(String query)
{
Dictionary<String, String> queryDict = new Dictionary<string, string>();
foreach (String token in query.TrimStart(new char[] { '?' }).Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries))
{
string[] parts = token.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 2)
queryDict[parts[0].Trim()] = HttpUtility.UrlDecode(parts[1]).Trim();
else
queryDict[parts[0].Trim()] = "";
}
return queryDict;
}
Actually, a useful improvement to Canning's answer that take care of decoding url-encoded values (like in the above solution) is:
public static Dictionary<string, string> ParseQueryString2(String query)
{
return Regex.Matches(query, "([^?=&]+)(=([^&]*))?").Cast<Match>().ToDictionary(x => x.Groups[1].Value, x => HttpUtility.UrlDecode( x.Groups[3].Value ));
}
One liner without HttpUtility
var dictionary = query.Replace("?", "").Split('&').ToDictionary(x => x.Split('=')[0], x => x.Split('=')[1]);
Yet another way to do it:
NameValueCollection nvcData = HttpUtility.ParseQueryString(queryString);
Dictionary<string, string> dictData = new Dictionary<string, string>(nvcData.Count);
foreach (string key in nvcData.AllKeys)
{
dictData.Add(key, nvcData.Get(key));
}
Most simple:
Dictionary<string, string> parameters = new Dictionary<string, string>();
for (int i = 0; i < context.Request.QueryString.Count; i++)
{
parameters.Add(context.Request.QueryString.GetKey(i), context.Request.QueryString[i]);
}
I stumbled across this post whilst looking for the same solution for an Azure WebJob, hopefully this helps others doing the same.
If you are coding an Azure WebJob you use the GetQueryParameterDictionary() extension method.
var queryParameterDictionary = request.GetQueryParameterDictionary();
where request is of type HttpRequest and queryParameterDictionary is now of type IDictionary<string, string>
You can just get it by decorating the parameter with the FromQueryAttribute
public void Action([FromQuery] Dictionary<string, string> queries)
{
...
}
P.S. If you want to get multiple values for each key you can change the Dictionary to Dictionary<string, List<string>>
Instead of converting HttpContext.Request.QueryString to Dictionary<>, try using
HttpContext.Request.Query
which already is a Dictionary<string, StringValues>
AspNet Core now automatically includes HttpRequest.Query which can be used similar to a dictionary with key accessors.
However if you needed to cast it for logging or other purposes, you can pull out that logic into an extension method like this:
public static class HttpRequestExtensions
{
public static Dictionary<string, string> ToDictionary(this IQueryCollection query)
{
return query.Keys.ToDictionary(k => k, v => (string)query[v]);
}
}
Then, you can consume it on your httpRequest like this:
var params = httpRequest.Query.ToDictionary()
Further Reading
How to parse a query string into a NameValueCollection in .NET
Convert query string to key-value pair in .Net
Is it possible to get Dictionary from query string?

Categories