I want to pass some arguments from my app like so:
app.exe mode=1 thread=single
and I want to convert these to a Dictionary of key-value pairs. Any one-line suggestions?
This is very basic and doesn't take error conditions into account:
var dictionary = args.Select(a => a.Split('='))
.ToDictionary(a => a[0], a => a.Length == 2 ? a[1] : null);
Some of the potential errors are:
=
Dealing with those makes it a little uglier:
var dictionary = args.Select(a => a.Split(new [] {'='}, 2))
.GroupBy(a => a[0], a => a.Length == 2 ? a[1] : null)
.ToDictionary(g => g.Key, g => g.FirstOrDefault());
The link Mitch shared to his blog post Parsing Command Line Arguments provides the answer you're probably looking for.
It contains a class that can be used to parse command line args into a Dictionary
of key/value pairs.
/// <summary>
/// Very basic Command Line Args extracter
/// <para>Parse command line args for args in the following format:</para>
/// <para>/argname:argvalue /argname:argvalue ...</para>
/// </summary>
public class CommandLineArgs
{
private const string Pattern = @"\/(?<argname>\w+):(?<argvalue>.+)";
private readonly Regex _regex = new Regex(
Pattern,
RegexOptions.IgnoreCase|RegexOptions.Compiled);
private readonly Dictionary<String, String> _args =
new Dictionary<String, String>();
public CommandLineArgs()
{
BuildArgDictionary();
}
public string this[string key]
{
get
{
return _args.ContainsKey(key) ? _args[key] : null;
}
}
public bool ContainsKey(string key)
{
return _args.ContainsKey(key);
}
private void BuildArgDictionary()
{
var args = Environment.GetCommandLineArgs();
foreach (var match in args.Select(arg =>
_regex.Match(arg)).Where(m => m.Success))
{
try
{
_args.Add(
match.Groups["argname"].Value,
match.Groups["argvalue"].Value);
}
// Ignore any duplicate args
catch (Exception) {}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With