我试图在列表中只获取奇数参数。这是我的一段代码
static void Main(string[] args)
{
var swictches = args.ToList().Select((x, index) => (index % 2) == 1);
var ss = swictches[0];
string test = doc.ReadAllPages();
Console.WriteLine(test.Substring(0, 1000));
Console.Read();
}
在参数列表中它有开关和参数。我正在尝试获取所有开关。当我运行此代码时,switches 变量如下所示:
false
true
false
而不是像这样
-i
-awq
-l
最佳答案
使用 Where
而不是 Select
:
var swictches = args.Where((x, index) => (index % 2) == 1).ToList();
此外,您不必调用 ToList()
使用 Where
/Select
. string[]
工具 IEnumerable<string>
同样,因此您可以在其上使用 LINQ。而不是调用 ToList
一开始将其称为最后一个方法,将结果实例化为List<string>
.
编辑:
正如评论中指出的那样。你应该使用 First
当您只需要序列中的第一个元素时,而不是调用 ToList()
并使用 [0]
在结果上。它会更快:
var ss = args.Where((x, index) => (index % 2) == 1).First();
关于c# - 如何只得到奇数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18705881/