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

标签 c# linq lambda

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/

相关文章:

C# Func<> 委托(delegate)参数转换错误

Java Lambda 表达式和事件信息

c# - 显示从数据库到 WPF 应用程序的多行

c# - 使用 LINQ 动态查询文件系统信息

c# - 将通用数据表转换为类型化数据表

c# - Linq - 项目列表 <A> 到分组列表 <B> 与列表 <B> 中的 C 对象

c# - 如何在 A 列或 B 列上加入 Linq 查询

c# - 转换为表达式主体似乎不起作用?

c# - 如何使用反射调用具有通用返回类型的方法

c# - WCF 双工回调,如何向所有客户端发送消息?