【问题标题】:Find if a Substring is Part of List/Array Directly直接查找子字符串是否是列表/数组的一部分
【发布时间】:2016-09-05 05:14:09
【问题描述】:

我有一个列表定义为:

List<string> content = new List<string>(){ "Hello This", "This is", "This" };

我想要一个代码来查找列表是否包含关键字 This,如果是,则获取它的第一次出现。

现有代码:

foreach(string line in content){
     if(line.Contains("This"))
          return line;
}

我想简单地知道是否有其他选择。如果我们知道完整的字符串,那么我们可以使用 List.Contains,但是对于子字符串,如何进行?

使用 .NET 2.0。请建议不要使用 LINQ。

【问题讨论】:

  • 你当前的代码有什么问题?
  • @DGibbs 没什么问题,但我想知道是否有更简单/直接的方法可以代替这个。
  • @B V Raman 这对我来说看起来非常简单。如果我不能使用 LINQ,我会这样做。我唯一建议的是确保您进行不区分大小写的比较/包含
  • 我认为这已经是没有 LINQ 的最简单的解决方案了。
  • 哪个版本的 C#?多个答案使用 lambda 表达式,但在 C# 3 之前不存在,后者是在 .NET 2.0 之后引入的。

标签: c# arrays string list substring


【解决方案1】:

这是您在 C#2.0 中搜索的内容:

List<string> content = new List<string>() { "Hello This", "This is", "This" };
string keyword = "This";
string element = content.Find(delegate(string s) { return s.Contains(keyword); });

【讨论】:

    【解决方案2】:

    Find()第一个符合指定条件的元素 谓词,如果找到的话;否则,T 类型的默认值Msdn

    Find() 可从NET Framework 2.0

    获得
     List<string> content = new List<string>() { "Hello This", "This is", "This" };
     string firstOccurance = content.Find(g => g.Contains("This"));
    

    【讨论】:

      【解决方案3】:

      正如MSDN 所述,FindIndexFramework 2.0 起可用,可用于解决您的问题。

      FindIndex 搜索与指定谓词定义的条件匹配的元素,并返回整个 List 中第一次出现的从零开始的索引。

      List<string> content = new List<string>() { "Hello This", "This is", "This" };
      var index = content.FindIndex(p => p.Contains("This"));
      if (index >= 0)
          return content[index];
      

      【讨论】:

        【解决方案4】:

        你可以使用 linq,这和你的 for 循环一样:

        return content.FirstOrDefault(x => x.Contains("This"));
        

        【讨论】:

        • 他会想要 FirstOrDefault 因为他不知道列表中包含他正在搜索的项目...
        • 谢谢,但是因为我在 .NET 2.0 上,所以没有 LINQ 的任何方法
        • Carra - 它的 linq "FirstOrDefault" 和 "Contains"。
        猜你喜欢
        • 1970-01-01
        • 2012-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 2019-07-19
        • 2012-12-19
        • 1970-01-01
        相关资源
        最近更新 更多