Casey Crookston
Casey Crookston

Reputation: 13945

Filter a list by using .StartsWith and a Regular Expression?

I have this class:

public class SimpleUser
{
    public int ProviderID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool ExistingUser { get; set; }
}

I have a List that I am filtering by the first letter of a property with in the object. This works great:

List<SimpleUser> filtersList = originalList.Where(s => s.LastName.StartsWith(alpaPage)).ToList();

But, here's my catch. For whatever reason, there are rows in this data where LastName is not a letter. Example: Contractor #2 where #2 is the last name. So on the UI, I give the users a list of filtering options. Like:

Etc. If they click on A, B, or C... no problem. But if they click on 123, now I need a separate filter to look for any LastName that does not start with a letter.

I'm pretty sure Regular Expressions will be involved here, but I am not seeing how to put all of this together.

List<SimpleUser> filtersList = originalList.Where(s => s.LastName.StartsWith(?????)).ToList();

I believe my regex would be

[^a-zA-Z]

But please correct me if I'm wrong. So I've got:

var regEx = new Regex("[^a-zA-Z]");

But after that. I'm lost. .StartsWith(... does not seem to take a RegEx. How do I format this?!?

Thanks!

Upvotes: 0

Views: 1620

Answers (2)

41686d6564
41686d6564

Reputation: 19641

I think Regex is an overkill for this. As mentioned in the comments, a simple char.IsLetter check on the first character of the LastName should do just fine:

List<SimpleUser> filtersList = 
    originalList.Where(s => !char.IsLetter(s.LastName[0])).ToList();

Complete example:

var originalList = new List<SimpleUser>()
{
    new SimpleUser() { LastName = "aaa" },
    new SimpleUser() { LastName = "bbb" },
    new SimpleUser() { LastName = "123" },
    new SimpleUser() { LastName = "#2" },
};

List<SimpleUser> filtersList = 
    originalList.Where(s => !char.IsLetter(s.LastName[0])).ToList();

foreach (var user in filtersList)
{
    Console.WriteLine(user.LastName);
}

Output:

123
#2

Upvotes: 1

Michał Turczyn
Michał Turczyn

Reputation: 37347

You could try this simple code:

List<string> strList = new List<string>() { "aBC", "1asdf", "123fasdf", "a1" };

strList = strList.Where(s => Regex.IsMatch(s, @"^[^a-zA-Z].+")).ToList();

Details: pattern ^[^a-zA-Z].+ will match string that start with character other than letter (upper or lowercase). Then, I use IsMatch method to see if match succeded.

So, in your case, you could put together your pattern like this:

string pattern = alpaPage + ".+";

In case of 123 option, alpaPage should equal to [^a-zA-Z].

Conclusion: use originalList.Where(s => Regex.IsMatch(s.LastName, @"^[^a-zA-Z].+").ToList();

Upvotes: 0

Related Questions