Search C # list using letters

I have a List<string> with some words. I want to get all the elements, the witch contains letters in this scheme: a00b0c000d - 0 is a random char, a,b,c,d - constantly contains characters in a string.

How can i do this? Can I only do this with Regex? There is no other solution?

+6
source share
5 answers

Well, instead of regex, you can use LINQ to check for specific characters at appropriate positions. But I would definitely prefer a regular expression.

 var result = yourList .Where(x => x[0] == "a") .Where(x => x[3] == "b") .Where(x => x[5] == "c") .Where(x => x[9] == "d") .ToList(); 
+5
source

Well, you can do this with Regex and LINQ:

 Regex yourRegex = new Regex(@"a..bc..d"); //if you want whole string match use ^a..bc..d$ var result = yourList.Where(yourRegex.IsMatch); 
+2
source

You can use the IndexOfAny() method for a row after a loop through List. IndexOfAny looks for a string for many values.

  List<string> words = new List<string>(); foreach(string word in words) { int match = word.IndexOfAny(new char[] {'a', 'b', 'c', 'd'}); if(match!=-1) { //Processing Logic here } } 
  • It reports the index of the first occurrence in this instance of any character in the specified array of Unicode characters.
  • The method returns -1 if the characters in the array are not found in this instance.
+1
source

An effective way would be to simply iterate over the list.

 List<string> matches = new List<string>(); myList.ForEach((x) => { if(x[0] == 'a' && x[3] == 'b' && x[5] == 'c' && x[9] == 'd') matches.Add(x); }); 

Or you can use LINQ, which may be a little slower, but is unlikely to become a bottleneck.

 var matches = myList.Where(x => x[0] == 'a' && x[3] == 'b' && x[5] == 'c' && x[9] == 'd').ToList(); 
+1
source

Without using Regex, you could probably do something in lines

  List<string> stromgs = new List<string>(); foreach (var s in stromgs) { var sa = s.Select(c => c.ToString(CultureInfo.InvariantCulture)).ToArray(); if (sa.Contains("a") && sa.Contains("b") && sa.Contains("c") && sa.Contains("d")) yield return s; } 

To get the results you need. I haven’t profiled this code, so it can be much slower than using regular expressions for everything I know, but it should give you a way to avoid regular expressions (which I usually do).

0
source

Source: https://habr.com/ru/post/950419/


All Articles