Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass key value pairs from console app to a Dictionary

Tags:

c#

linq

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?

like image 587
dqm Avatar asked Dec 21 '22 05:12

dqm


2 Answers

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:

  • Duplicate names
  • More than one =

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());
like image 108
Bennor McCarthy Avatar answered Feb 19 '23 08:02

Bennor McCarthy


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) {}
        }
    }
}
like image 20
3 revs, 2 users 95% Avatar answered Feb 19 '23 09:02

3 revs, 2 users 95%