简体   繁体   中英

Check if List of Tuples of Strings appear in string in order

I have a list of Tuples that contain combinations of strings that I want to check for in a Queue property of my text file object (newFile). The Queue is a queue of strings called Lines.

I'm not sure the list of Tuples is the way to go but I only want a true result if Item1 and Item2 of any Tuple are found (in Item1 then Item2 order) in any line. Here's my best shot and I just can't figure out how to write the LINQ statement.

List<Tuple<string,string>> codes = new List<Tuple<string, string>>()
   {
      new Tuple<string, string>("01,", "02,"),
      new Tuple<string, string>("02,", "03,"),
      new Tuple<string, string>("03,", "88,"),
      new Tuple<string, string>("88,", "88,"),
      new Tuple<string, string>("89,", "90,")                 
   };

bool codesFound = newFile.Lines
                      .Any(Regex.Match(codes.Select(x => (x.Item1 + "(.*)" + x.Item2)));

Something like this should get you the result you're after:

bool found = newFile.Lines
    .Any(x => codes.Select(y => x.IndexOf(y.Item1) > -1 && x.IndexOf(y.Item2) > -1 
                            && x.IndexOf(y.Item1) < x.IndexOf(y.Item2)).Any(z => z));

Just in case you want to check the regex way, here you are:

bool codesFound = newFile.Lines.Any(p =>
              Regex.IsMatch(p, string.Join("|", codes.Select(x => x.Item1 + ".+" + x.Item2).ToList()))
              );

Here, I join all patterns into a single string like 01,.+02,|02,.+03, ... and then check if there is any string in the input array that satisfies this condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM