【问题标题】:List search by index?按索引列出搜索?
【发布时间】:2015-02-07 23:04:01
【问题描述】:

我正在尝试搜索第一个 list 项 的 index,它的值为 "hello",它是 index 高于 15。 这显然不是这样,因为当我引用 p 时,我指的是 value,而不是 string 本身(IndexOf 查找"hello" 在列表中第一次出现的索引,因为 p == string)

int soucasny = list1.FindIndex(p => p == "hello" || list1.IndexOf(p) > 15);

有没有办法达到预期的结果?选择大概?

【问题讨论】:

    标签: c# list search indexing


    【解决方案1】:

    您可以为IndexOf指定起始索引

    int soucasny = list1.IndexOf("hello", 15);
    

    【讨论】:

    • 我认为这行不通,不是吗?由于列表中的对象与您传递的常量字符串不同,不是吗?
    • 哦,是的,它会的。我想是这样。立即测试。
    • @Jauch 为什么不呢?字符串通过它们的值进行比较。这段代码与 OP 的代码做同样的事情。如果他不是在寻找精确匹配,这应该在问题中指定
    • 是的,我怀疑它是否在列表中有效,但我测试过,是的,它有效:) 这种方法的唯一问题是如果列表中的项目少于 16 个...
    • 确实而且非常好。无需使用 FindIndex 等。在这种情况下,这是我的错,不知道 IndexOf 有一个需要 2 个参数的重载。三,甚至。不知何故错过了这个。谢谢。
    【解决方案2】:

    使用List<T>.FindIndex Method (Int32, Predicate<T>),它接受一个谓词并指定开始搜索的索引,例如:

    int soucasny = list1.FindIndex(15, p => p == "hello");
    

    如果你有List<string>,那么使用List<T>.IndexOf 会给你结果,但如果你有一个自定义对象列表,那么你可能需要谓词。喜欢:

    List<Student> studentList = new List<Student>();
    int index = studentList.FindIndex(15, p=> p.StudentName == "Some Name");
    

    【讨论】:

      【解决方案3】:

      @Selman22 为您的确切问题提供最正确和最有效的答案。对于您可能有非List 序列或需要从过滤器表达式中访问元素索引的情况,我仅提供以下内容作为附录:

      public static int FirstIndexWhere<T>(
          this IEnumerable<T> sequence,
          Func<T, int, bool> predicate)
      {
          if (sequence == null)
              throw new ArgumentNullException("sequence");
          if (predicate == null)
              throw new ArgumentNullException("predicate");
      
          var index = 0;
      
          for (var enumerator = sequence.GetEnumerator(); enumerator.MoveNext(); ++index)
          {
              if (predicate(enumerator.Current, index))
                  return index;
          }
      
          return -1;
      }
      

      示例用法:

      int soucasny = list1.FirstIndexWhere((p, i) => p == "hello" && i > 15);
      

      【讨论】:

        猜你喜欢
        • 2018-05-06
        • 1970-01-01
        • 1970-01-01
        • 2021-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-23
        • 1970-01-01
        相关资源
        最近更新 更多