gpt4 book ai didi

c# - List.Any 得到匹配的字符串

转载 作者:可可西里 更新时间:2023-11-01 03:03:50 25 4
gpt4 key购买 nike

FilePrefixList.Any(s => FileName.StartsWith(s))

我可以在这里获取s值吗?我想显示匹配的字符串。

最佳答案

Any仅确定是否存在匹配项,除 bool 外不返回任何内容它需要执行查询。

您可以使用 WhereFirst/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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com