我想从我的应用程序中传递一些参数,如下所示:
app.exe mode=1 thread=single
我想将这些转换为键值对字典。任何单行建议?
这是非常基本的,不考虑错误条件:
var dictionary = args.Select(a => a.Split('='))
.ToDictionary(a => a[0], a => a.Length == 2 ? a[1] : null);
一些潜在的错误是:
=
处理这些会使它变得更丑陋:
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());
Mitch在他的博客文章Parsing Command Line Arguments中分享的链接提供了您可能正在寻找的答案。
它包含一个类,可用于将命令行参数解析Dictionary
为键/值对。
/// <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) {}
}
}
}
我确实删除了它,但我将把它留在这里只是因为 OP确实要求提供“单行建议”。:)
var result = (from item in data.Split(' ') let keyValue = item.Split('=') select new {Key = keyValue[0], Value = keyValue[1]}).ToDictionary(item => item.Key, item => item.Value);
感谢这个问题和这个问题的所有现有答案
这里的原始问题要求一个单行的答案,所以这里是一个。
private static void Main(string[] args)
{
Dictionary<string, string> cmdArgs = args.Select(s => new Regex(@"/(?<name>.+?):(?<val>.+)").Match(s)).Where(m => m.Success).ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);
}
不是单行的,而是我用于格式如下的参数的有点可读的解决方案:
-arg1 bla -arg2 ble
var argsDict = new Dictionary<string, string>();
var argKeys = args.Where(a => a.StartsWith("-")).ToArray();
foreach (var argKey in argKeys)
{
var keyIndex = Array.IndexOf(args, argKey);
var argValue = e.Args.ElementAtOrDefault(keyIndex + 1);
try
{
args.Add(argKey, argValue);
}
catch
{
Console.WriteLine("Startup arguments invalid.");
return;
}
}