Reputation: 473
I'm trying to convert command line arguments to different formats. For example, if I'm trying to get a specific user, it would be GetUser=UserName
, but I also have methods that don't need the equals sign, such as GetAllUsers
. Right now I'm currently splitting on the =
but I don't need to do that for all commands. I tried setting it to a conditional, where if =
is detected, it will split, otherwise it will just take the argument as a string, but I'm getting Cannot implicitly convert type 'string' to 'System.Collections.Generic.Dictionary<string, string>
Code:
public static Dictionary<string, string> ParseArgs(string[] args)
{
Dictionary<string, string> results = new Dictionary<string, string>();
foreach (string arg in args)
{
string[] parts = arg.Split('=');
if (parts.Length > 1)
{
results[parts[0]] = parts[1];
continue;
}
else
{
results = Convert.ToString(arg);
}
}
return results;
}
Upvotes: 1
Views: 599
Reputation: 1985
In the else part, you are trying to assign string to dictionary via the statement results = Convert.ToString(arg);
So, please change else part with something like as shown below:
public static Dictionary<string, string> ParseArgs(string[] args)
{
Dictionary<string, string> results = new Dictionary<string, string>();
foreach (string arg in args)
{
string[] parts = arg.Split('=');
if (parts.Length > 1)
{
results[parts[0]] = parts[1];
// continue; no need to use continue, as there are no more statements after this if-else, loop will anyway continue. but please uncomment if you have any in your actual code.
}
else
{
results[arg] = arg; // assuming arg string in args won't repeat, meaning its unique. Otherwise please use ContaineKey if condition before adding or over-writing.
}
}
return results;
}
Upvotes: 0
Reputation: 643
You're trying to assign a string to a dictionary object. If you want a collection (like Dictionary) then you should use the Add method like so:
foreach (string arg in args)
{
string[] parts = arg.Split('=');
if (parts.Length > 1)
{
//results[parts[0]] = parts[1];
results.Add(parts[0], parts[1]);
continue;
}
else
{
results.Add("GetUser", arg);
}
}
I've forced it to be "GetUser" as the value here, but you may actually want something different. Your dictionary is using Key-Value pairs and you would say results["GetUser"] to return a string for "GetUser". You could also use TryGetValue to validate that GetUser was actually provided.
Additionally, if you just want to return the string that's after GetUser (e.g. Username), then you could change results to a string and just assign that directly and skip the whole use of a Dictionary, which seems overkill for your sample (perhaps your real project is much more complex though).
Upvotes: 1