[英]How to return the String from String Array that contains a particular Substring in C#?
I am taking string array of arguments of command line and checking if there is any argument which contains a ".xml" substring我正在获取命令行的 arguments 的字符串数组,并检查是否有任何包含“.xml”的参数 substring
string[] args = this.Command.GetCommandLineArgs();
string strXMLFileName = string.Empty;
for (int i = 0; i < args.Length; ++i)
{
if (args[i].Contains(".xml"))
{
strXMLFileName = args[i];
}
}
I searched a bit in List<string> methods, but couldn't find anything that could simplify the process我在 List<string> 方法中搜索了一下,但找不到任何可以简化过程的东西
I am assuming there is only 1 argument with ".xml" substring我假设只有 1 个参数带有“.xml” substring
Is there any built-in C# method with which I can do this without manually iterating through the string array是否有任何内置的 C# 方法,我可以使用它来执行此操作而无需手动遍历字符串数组
You can try SingleOrDefault()
, so that you will get an exception if there are multiple .xml
files are available in the list.您可以尝试SingleOrDefault()
,这样如果列表中有多个.xml
文件可用,您将得到一个异常。 I used EndsWith()
instead of Contains()
, so that condition will check file ends with .xml
or not.我使用EndsWith()
而不是Contains()
,因此该条件将检查文件是否以.xml
结尾。
var strXMLFileName = args.SingleOrDefault(x => x.EndsWith(".xml")) ?? string.Empty;
If you are sure that string with .xml
is in array:如果您确定带有.xml
的字符串在数组中:
var arr = new string[]
{
"file1.txt",
"file2.xml",
"file3.xml",
};
var strXMLFileName = arr.First(x => x.EndsWith(".xml"));
System.Console.WriteLine(strXMLFileName);
If you are not sure:如果您不确定:
var arr = new string[]
{
"file1.txt",
"file2.xml",
"file3.xml",
};
var strXMLFileName = arr.FirstOrDefault(x => x.EndsWith(".xml"));
System.Console.WriteLine(strXMLFileName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.