FilePrefixList.Any(s => FileName.StartsWith(s))
我可以在这里获取s
值吗?我想显示匹配的字符串。
最佳答案
Any
仅确定是否存在匹配项,除 bool
外不返回任何内容它需要执行查询。
您可以使用 Where
或 First
/FirstOrDefault
:
string firstMastch = FilePrefixList.FirstOrDefault(s => FileName.StartsWith(s)); // null if no match
var allMatches = FilePrefixList.Where(s => FileName.StartsWith(s));
string firstMastch = allMatches.FirstOrDefault(); // null if no match
所以 Any
如果您只需要知道是否匹配就可以了,否则您可以使用 FirstOrDefault
获得第一场比赛或null
(在引用类型的情况下)。
自 Any
需要执行查询,这效率较低:
string firstMatch = null;
if(FilePrefixList.Any(s => FileName.StartsWith(s)))
{
// second execution
firstMatch = FilePrefixList.First(s => FileName.StartsWith(s));
}
如果您想将所有匹配项放入单独的集合中,例如 List<string>
:
List<string> matchList = allMatches.ToList(); // or ToArray()
如果你想输出所有匹配你可以使用String.Join
:
string matchingFiles = String.Join(",", allMatches);
关于c# - List.Any 得到匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31984146/