博客
关于我
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/

你可能感兴趣的文章
ORACLE MERGE INTO (2)
查看>>
oracle ogg 单实例双向复制搭建(oracle-oracle)--Oracle GoldenGate
查看>>
Oracle ora-12514报错解决方法
查看>>
oracle ORA-14402 OGG-01296
查看>>
oracle package包头和package body包体例子
查看>>
oracle partition by list,深入解析partition-list 分区
查看>>
Oracle PL/SQL Dev工具(破解版)被植入勒索病毒的安全预警及自查通告
查看>>
oracle pl/sql 导出用户表结构
查看>>
Oracle PLSQL Demo - 17.游标查询个别字段(非整表)
查看>>
【C/C++学院】(6)构造函数/析构函数/拷贝构造函数/深copy浅copy
查看>>
oracle rac 安装 PRVG-13606 ntp 同步报错解决过程
查看>>
Oracle RAC性能调整的方案
查看>>
oracle rac集群的东西之QQ聊天
查看>>
UML— 用例图
查看>>
Oracle Schema Objects——Tables——Table Compression
查看>>
oracle scott趣事
查看>>
oracle script
查看>>
Oracle select表要带双引号的原因
查看>>
Oracle SOA Suit Adapter
查看>>
Oracle Spatial GeoRaster 金字塔栅格存储
查看>>