I have a web service which receive a string.
This string contains multiple keys => values which are concatenated with the character ‘+’.
I must validate each value (“required”, “not empty”), and assign each to a variable with the same name.
Here is how I build the Dictionary from the string :
string firstname;
string lastname;
string amount;
string request = "firstname=foo+lastname=bar+amout=100.58";
Dictionary<string, string> arguments = new Dictionary<string, string>();
request.Split('+').ToList<string>().ForEach(p =>
{
string[] tmp = p.Split('=');
if (tmp.Length == 2)
arguments.Add(tmp[0], tmp[1]);
});
// Validate and assign : How I do with one value : (I must find a better way)
bool isValid = true;
// check "firstname"
if(arguments.ContainsKey("firstname") && string.IsNullOrWhiteSpace(arguments["firstname"]) == false)
{
firstname = arguments["firstname"];
}
else
{
isValid = false;
Logger.Write("Invalid argument : firstname");
}
// Do this for about 20 arguments, it becomes huge...
if(isValid)
{
Console.WriteLine(firstname); // Displays foo
Console.WriteLine(lastname); // Displays bar
Console.WriteLine(amout); // Displays 100.58
}
Thanks, and sorry for spelling mistakes, I’m French.
I think you want something like this, but since you didn’t acutally ask a question I’m just guessing:
Also, I would question the use of ToList->ForEach if this was in front of me in a code review. You want to avoid side effects in Linq, I would write it with a traditional foreach like:
Edit 2 – You should encapsulate the logic in a method:
Now you can say:
TryGetValuewould make an excellent extension method:Now the calling code would look like:
Last edit –
A note on extention methods – Yes they are neat, but it’s also easy to accidently get in a bad situation overusing them. Read up on msdn and blogs about them, follow the guidelines. Avoid extensions on generic types like
object,stringect.In my projects I always lay out extension methods in distinct namespaces depending on the type they interact with, which forces classes that wish to use them to be very explicate about it like:
and consuming code would have
usingclauses to match:to pull in just the extensions your interested in, no more.