Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching list C# by containing letters

Tags:

c#

.net

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?

like image 895
whoah Avatar asked Jul 27 '13 10:07

whoah


4 Answers

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();
like image 199
Dennis Traub Avatar answered Nov 09 '22 00:11

Dennis Traub


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);
like image 37
It'sNotALie. Avatar answered Nov 09 '22 02:11

It'sNotALie.


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.
like image 1
Bhushan Firake Avatar answered Nov 09 '22 00:11

Bhushan Firake


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();
like image 1
keyboardP Avatar answered Nov 09 '22 00:11

keyboardP