whoah
whoah

Reputation: 4443

Searching list C# by containing letters

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

How can I do this? Can I do this only with Regex? There isn't any other solution?

Upvotes: 6

Views: 3040

Answers (5)

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22794

Well, you can do it with Regex and LINQ:

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

Upvotes: 2

keyboardP
keyboardP

Reputation: 69372

An efficient way would be to just 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 might be slightly slower but unlikely to be a bottleneck.

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

Upvotes: 1

Bhushan Firake
Bhushan Firake

Reputation: 9458

You can use IndexOfAny() method for string after looping through List.IndexOfAny searches 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 a specified array of Unicode characters.
  • The method returns -1 if the characters in the array are not found in this instance.

Upvotes: 1

aevitas
aevitas

Reputation: 3833

Without using Regex, you could probably do something along the lines of

        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 are after. I haven't profiled this code so it could be a lot slower than using regular expressions for all I know, but it should give you a way to avoid Regex altogether (which is something I usually tend to do).

Upvotes: 0

Dennis Traub
Dennis Traub

Reputation: 51634

Well, instead of a regex you can use LINQ to check for specific characters in the respective positions. But I'd 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();

Upvotes: 5

Related Questions