0

I have a model with a property string that can be the format "00000044" so assuming I'm querying a List of

public class Foo
{
     private string MemberNo { get; set; }
}

populated from Entity Framework,

and our set includes the following:

"00000044" include this
"44000000" include this
"20440000" exclude this

how to write a query that will exclude anything with non-zero number to the left of our search criteria "44"

Is it possible to combine Regex with linq or is there a smarter way?

Ta

MikeW
  • 4,749
  • 9
  • 42
  • 83
  • How about `0*44`? Matches none or any amount of zeros and then 44. You can also do `foo.MemberNo.TrimStart('0').StartsWith("44")` to see if the "44" is the first non-zero match. – SimpleVar May 29 '12 at 03:09
  • hey thanks for response. could you show me the linq query? We're ok with the 0*44 regex - just how to write the query - i forgot to add this is querying EF - apolz. – MikeW May 29 '12 at 03:10
  • Read about the LIKE keyword in SQL queries, because you don't want to pull all the data and then filter it, but better filter it DB-wise. – SimpleVar May 29 '12 at 03:12
  • ..once again displeased the SO gods... – MikeW May 29 '12 at 03:29
  • @MikeW are you talking about the down vote? – Yuriy Faktorovich May 29 '12 at 05:01

2 Answers2

6
var filteredFoos = myFoos
    .Where(foo => foo.MemberNo.TrimStart('0').StartsWith("44"));

Now this is if you want to bring back all Foos, but if you'd like to use the Entity Framework, look at this answer to translate it correctly.

Community
  • 1
  • 1
Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
1
var result = fooList.Where(foo => Regex.IsMatch(foo.MemberNo, @"^0*44\d*$"));

You'll also need to make the MemberNo property public.

Edit

Or alternatively, a regex-free version:

var result = fooList.Where(foo => foo.MemberNo.TrimStart('0').StartsWith("44"));
Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116
  • I'd stay away from regex because it sounds like the 44 may be an enterable search field. – Yuriy Faktorovich May 29 '12 at 03:14
  • @YuriyFaktorovich In that case it's fairly easy to build a regex pattern on the fly, and if you have it in a variable with a meaningful name I think it ends up being more readable. Having said that see my edit for a regex-free version which would probably perform better if there's a lot of `Foo` to be filtered. – Andrew Cooper May 29 '12 at 03:25
  • @YuriyFaktorovich And then I noticed it's the same as your answer. Doh! – Andrew Cooper May 29 '12 at 03:26
  • This was a great answer, the answer I marked is better for my overall understanding , but I appreciate the response - this works perfectly. – MikeW May 29 '12 at 03:27