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

前端 未结 5 1663
长发绾君心
长发绾君心 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:56

    I didn't see a shorter solution than yours. But I think the solution you propose only works if first string doesn't appear twice in the list. For example, if the list was:

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

    I think your proposal will not work because first FindIndex will return the index of the first "D", which is not followed by "E".

    A posible alternative could be (should be tested to be sure):

        int index=-1;
        Parallel.For(0, list.Count - 1, i =>
        {
          if (list[i] == "D" && list[i + 1] == "E")
          {
              Interlocked.Exchange(ref index, i);
          }
        }); 
    //after the loop, if index!=-1, sublist was found and starts at index position
    

    Not shorter, of course, but can be faster if list is very large, because using Parallel.For. A limitation is that if the sublist appears several times, you can obtain the index of any of them (not necessarily the first one).

提交回复
热议问题