我想从我的应用程序中传递一些参数:
app.exe mode=1 thread=single
我希望将它们转换为键值对字典。有任何一线建议吗?
答案 0 :(得分:7)
这是非常基本的,不会考虑错误条件:
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());
答案 1 :(得分:3)
Mitch shared到他的博文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) {}
}
}
}
答案 2 :(得分:0)
我确实删除了这个,但我会把它留在这里只是因为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);
答案 3 :(得分:0)
感谢此问题和this question
的所有现有答案这里的原始问题要求一行答案,所以这里有一个。
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);
}
答案 4 :(得分:-1)
不是单行的,而是一种可读的解决方案,我用于格式如下的参数:
-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;
}
}