简体   繁体   English

如何从 C# 中包含特定 Substring 的字符串数组返回字符串?

[英]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 use LINQ :您可以使用LINQ

var strXMLFileName = args.FirstOrDefault(x => x.Contains(".xml"));

Will yield null is there is no such argument.如果没有这样的论点,将产生null


NB: For the search string ".xml" , EndsWith is usually more appropriate than Contains .注意:对于搜索字符串".xml"EndsWith通常比Contains更合适。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM