【问题标题】:How to skip to substring in list如何跳到列表中的子字符串
【发布时间】:2014-07-03 19:41:26
【问题描述】:

我正在使用这个:

var temp =  conLines.Select((l, i) => new {l, i}).FirstOrDefault(r => (r.l.IndexOf(item.firstParam) >= 0 
     && r.l.IndexOf(item.secondParam) >= 0)
     && (r.l.IndexOf(item.firstParam) < r.l.IndexOf(item.secondParam)
));

但我不想在第一次找到 conLines 的某个子字符串(列表)之前开始“FirstOrDefault”。

例子:

conLines 看起来像这样:

NAME:

NOTES:

REVISION HISTORY:


format AT 1024 1  4

      1 AC       BUS      ENUM     0030 04    0 0 1/1   632

        NORMAL   04096 1  0,1

      2 AC       BUS-02   ENUM     00C0 06    0 0 1/1   632

        NORMAL   04096 1  0,1

我不希望它在下一行之后才开始寻找“FirstOrDefault”,但重要的是我仍然在整个 conLines 列表的上下文中跟踪 temp.i

format AT 1024 1  4 

我想 SkipWhile 和 StartsWith 可能有效,但我没有取得任何成功

【问题讨论】:

    标签: c# linq list lambda


    【解决方案1】:

    您的解决方案很接近。只需在.FirstOrDefault 之前添加.SkipWhile(o =&gt; o.l!= "format AT 1024 1 4")

    【讨论】:

      【解决方案2】:

      SkipWhile 应该可以工作:

      conLines.Select((s, i) => new {s, i})
              .SkipWhile(si => si.s != "format AT 1024 1  4")
              .Skip(1)         // skip to next line 
              .FirstOrDefault(si => si.s.IndexOf(item.firstParam) >= 0 
                                 && si.s.IndexOf(item.secondParam) >= 0
                                 && si.s.IndexOf(item.firstParam) < si.s.IndexOf(item.secondParam)
                             );
      

      请注意,第二个 IndexOf 是多余的 - 如果 A >= 0 且 A = 0。

      【讨论】:

      • 这会在 Select() 之后执行吗?我在应用 AnonymousType#1 类型的操作数时遇到错误
      • 您可能不需要Select。我假设 conLines 是一个字符串集合 - 如果没有将结构添加到您的问题中。
      • 是否可以将 Select 保留在其中?我正在尝试跟踪在 conLines 中找到 FirstOrDefault 的索引
      • 当然 - 我会加回来的。
      • conLines 是一个字符串集合。由于我将 SkipWhile 放在 Select 和 FirstOrDefault 之间,所以无论什么原因都会发生错误
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 2023-03-28
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 2012-10-23
      相关资源
      最近更新 更多