How to find a sub-list of two consecutive items in a list using Linq

前端 未结 5 1660
长发绾君心
长发绾君心 2021-01-26 19:56

Suppose that we have a list of strings like

\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"

Now I\'d like to search for a sub-list of

5条回答
  •  星月不相逢
    2021-01-26 20:45

    I don't think LINQ is appropriate here.

    A more efficient solution could be to find "D" then just check it isn't at the end and that "E" is at the next index:

    int i = list.FindIndex(x => x == "D");
    int p = (i < list.Count - 1) && (list[i + 1] == "E") ? i : -1;
    

    This avoids looping twice to find both indices, and also still matches if "E" appears next to "D" but also before it, e.g. {"E", "C", "D", "E"}

提交回复
热议问题