Skip to main content
 首页 » 编程设计

C# super 花哨的 LINQiness

2024年02月24日21zhenyulu

我正在尝试编写一种动态类型的命令行处理器,其中我有一个字典,其中的键是可能的参数,成员是一个 Action,其中字符串是命令行上传递的参数之间的文本。希望能够通过添加 params 数组并在字典中写入操作来添加参数。

是的,我意识到这是为了简化维护而过度复杂化实现的毫无意义的练习。主要是想给自己压力,学习更多的 linq。

这是我的字典:

    private static Dictionary<string[], Action<string>> _commandLineParametersProcessor = new Dictionary<string[], Action<string>>() 
{ 
    { 
        new string[] {"-l", "--l", "-log", "--log"}, 
        (logFile) =>   
            { 
                _blaBla.LogFilePath = logFile; 
            } 
    }, 
    { 
        new string[] { "-s", "--s", "-server", "--server" }, 
        (server) =>   
            { 
                ExecuteSomething(server); 
                _blaBla.Server = server; 
            } 
    } 
}; 

采用 string[] args 的最优雅机制是什么,而不仅仅是关联属于任何字典键数组的成员,而是 Aggregate((x,y) => string.Format("{0} {1 }", x, y)) args[] 成员之间的元素序列(认为 TakeWhile() 以某种方式适合这里)将包含在任何键数组中,并将它们传递给相应键的值成员。

我们都无数次地编写过这些小型命令行处理器,虽然显然一个简单的循环和切换总是绰绰有余,但正如我所说,这又是一个试图强调我的 linq 技能的练习。所以请不要提示我过度设计,那部分是显而易见的。

更新: 为了使这可能更容易一些,这是一种非 linq 方式来做我正在寻找的事情(可能不完美,这只是即兴发挥):

Action<string> currentAction; 
string currentActionParameter; 
for(int i = 0; i < e.Args.Length; i++) 
{ 
    bool isParameterSwitch = _commandLineParametersProcessor.Keys.Any((parameterChoices) => parameterChoices.Contains(e.Args[i])); 
 
    if (isParameterSwitch) 
    { 
        if (!string.IsNullOrEmpty(currentActionParameter) && currentAction != null) 
        { 
            currentAction(currentActionParameter); 
 
            currentAction = null; 
            currentActionParameter = ""; 
        } 
        currentAction = _commandLineParametersProcessor[_commandLineParametersProcessor.Keys.Single((parameterChoices) => parameterChoices.Contains(e.Args[i]))]; 
    } 
    else 
    { 
        currentActionParameter = string.Format("{0} {1}", currentActionParameter, e.Args[i]); 
    } 
} 

这不是一个完全糟糕的方法,我只是想知道是否有人可以使用 linq 或其他方式稍微简化它,尽管我猜这可能是最简单的形式..

请您参考如下方法:

借用了 Adam Robinson 的一半答案(顺便说一句 +1),但意识到字典永远无法通过键访问,而您只想运行 Actions 而不是构建字符串...

var inputCommands = args 
    .Select((value, idx) => new { Value = value, Group = idx / 2 }) 
    .GroupBy(x => x.Group)  
    .Select(g => new   
    {   
      Command = g.First().Value,   
      Argument = g.Last().Value   
    }).ToList(); 
 
inputCommands.ForEach(x =>  
{ 
  Action<string> theAction =  
  ( 
    from kvp in commands 
    where kvp.Key.Contains(x.Command) 
    select kvp.Value 
  ).FirstOrDefault(); 
  if (theAction != null) 
  { 
    theAction(x.Argument); 
  } 
} 

kvp.Key.Contains真的打败了字典的全部意义。我将其重新设计为 Dictionary<string, Action<string>> .然后你可以说

inputCommands.ForEach(x =>  
{ 
  if (commands.ContainsKey(x.Command)) 
  { 
    commands[x.Command](x.Argument); 
  } 
} 

PS:我记得我写的 C# 代码比这要多得多。


我必须承认您可能想要收集操作,而不是运行它们。这是代码:

var todo = 
( 
  from x in inputCommands 
  let theAction =  
  ( 
    from kvp in commands 
    where kvp.Key.Contains(x.Command) 
    select kvp.Value 
  ).FirstOrDefault() 
  where theAction != null 
  select new { TheAction = theAction, Argument = x.Argument } 
).ToList();