添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
眼睛小的铁链  ·  C# ...·  1 年前    · 

使用LINQ查询,可以使用 Contains() 方法对字符串进行部分匹配。例如,以下代码段将在 myList 中查找包含 "hello" 的字符串:

List<string> myList = new List<string>{"hello world", "goodbye", "hi there"};
List<string> matches = myList.Where(x => x.Contains("hello")).ToList();

此代码段将返回一个 matches 列表,其中包含 "hello world" 这个字符串。

要使用通配符进行匹配,可以使用 String.Contains() 方法的变体,即 String.Contains(string, StringComparison) 方法。此方法允许使用 StringComparison 枚举来指定不同的匹配选项。

例如,以下代码段将在 myList 中查找以 "he" 开头的字符串:

List<string> myList = new List<string>{"hello world", "goodbye", "hi there"};
List<string> matches = myList.Where(x => x.Contains("he", StringComparison.OrdinalIgnoreCase)).ToList();

这将返回一个 matches 列表,其中包含 "hello world" 和 "hi there" 两个字符串,因为它们以 "he" 开头。

  • 使用正则表达式
  • 另一种方法是使用正则表达式。可以使用 Regex.IsMatch() 方法对字符串进行正则表达式匹配。例如,以下代码段将在 myList 中查找包含 "he" 和 "llo" 的字符串:

    List<string> myList = new List<string>{"hello world", "goodbye", "hi there"};
    List<string> matches = myList.Where(x => Regex.IsMatch(x, "he.*llo", RegexOptions.IgnoreCase)).ToList();
    

    此代码段将返回一个 matches 列表,其中包含 "hello world" 这个字符串。

    在这个例子中,正则表达式 "he.*llo" 用于匹配以 "he" 开头和以 "llo" 结尾的字符串。RegexOptions.IgnoreCase 参数指定匹配不区分大小写。

    以上就是在C#的List中使用通配符进行字符串匹配的方法。希望能够帮助到你。

  •