【问题标题】:How can I use Linq to to determine if this string EndsWith a value (from a collection)?如何使用 Linq 来确定此字符串 EndsWith 是否有值(来自集合)?
【发布时间】:2018-01-09 23:25:05
【问题描述】:

我试图找出一个字符串值EndsWith 是否是另一个字符串。这个“其他字符串”是集合中的值。我正在尝试将其作为字符串的扩展方法。

例如。

var collection = string[] { "ny", "er", "ty" };
"Johnny".EndsWith(collection); // returns true.
"Fred".EndsWith(collection); // returns false.

【问题讨论】:

    标签: .net linq-to-objects


    【解决方案1】:
    var collection = new string[] { "ny", "er", "ty" };
    
    var doesEnd = collection.Any("Johnny".EndsWith);
    var doesNotEnd = collection.Any("Fred".EndsWith);
    

    你可以创建一个字符串扩展来隐藏Any的用法

    public static bool EndsWith(this string value, params string[] values)
    {
        return values.Any(value.EndsWith);
    }
    
    var isValid = "Johnny".EndsWith("ny", "er", "ty");
    

    【讨论】:

      【解决方案2】:

      .NET 框架没有内置任何内容,但这里有一个扩展方法可以解决问题:

      public static Boolean EndsWith(this String source, IEnumerable<String> suffixes)
      {
          if (String.IsNullOrEmpty(source)) return false;
          if (suffixes == null) return false;
      
          foreach (String suffix in suffixes)
              if (source.EndsWith(suffix))
                  return true;
      
          return false;
      }
      

      【讨论】:

      • 干杯安德鲁。是的,这(或多或少)是我已经拥有的。我想看看如何用 Linq 来做这个(所以我可以学习它)。
      【解决方案3】:
      public static class Ex{
       public static bool EndsWith(this string item, IEnumerable<string> list){
         foreach(string s in list) {
          if(item.EndsWith(s) return true;
         }
         return false;
       }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-03-30
        • 2014-09-20
        • 2017-11-01
        • 2018-01-06
        • 2015-10-21
        • 1970-01-01
        • 1970-01-01
        • 2020-03-03
        • 1970-01-01
        相关资源
        最近更新 更多