博客
关于我
Linq to object 技巧、用法集锦
阅读量:800 次
发布时间:2023-01-31

本文共 975 字,大约阅读时间需要 3 分钟。

要判断字符串数组里的元素是否在字符串中出现,可以用Contains方法逐个检查。以下展示了两种实现方法。

方法一:使用 LINQ

using System.Linq;public class Program{    static void Main(string[] args)    {        string str = "你在他乡还好吗?";        string[] WordList = new string[]        {            "他乡",            "家庭",            "还好",            "怎么"        };        int count = WordList.Count(m => str.Contains(m));        Console.WriteLine(count);        Console.ReadKey();    }}

方法二:逐个检查循环

public class Program{    static void Main(string[] args)    {        string str = "你在他乡还好吗?";        string[] WordList = new string[]        {            "他乡",            "家庭",            "还好",            "怎么"        };        int count = 0;        foreach (string word in WordList)        {            if (str.Contains(word))                count++;        }        Console.WriteLine(count);        Console.ReadKey();    }}

代码解释

两种方法都通过检查每个字符串是否包含在主字符串中来统计出现次数。

优点

  • 简洁性:LINQ代码简洁易读。
  • 性能:对于小型数据集,两种方法性能相当。

结果

编译并运行这段代码,会输出2,表示有两个数组元素出现在原字符串中。

转载地址:http://gkwfk.baihongyu.com/

你可能感兴趣的文章
nginx 常用配置记录
查看>>
nginx 开启ssl模块 [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx
查看>>
Nginx 我们必须知道的那些事
查看>>
Nginx 源码完全注释(11)ngx_spinlock
查看>>
Nginx 的 proxy_pass 使用简介
查看>>
Nginx 的配置文件中的 keepalive 介绍
查看>>
Nginx 结合 consul 实现动态负载均衡
查看>>
Nginx 负载均衡与权重配置解析
查看>>
Nginx 负载均衡详解
查看>>
nginx 配置 单页面应用的解决方案
查看>>
nginx 配置https(一)—— 自签名证书
查看>>
nginx 配置~~~本身就是一个静态资源的服务器
查看>>
Nginx 配置清单(一篇够用)
查看>>
Nginx 配置解析:从基础到高级应用指南
查看>>
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>