Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL query to determine if value starts with numeric

I have a project where I query users by first letter:

repository.GetAll().Where(q => q.BrukerIdent.StartsWith(letter.ToString())).ToList();

..where repository.GetAll() returns an IQueryable<Bruker>, BrukerIdent is a string that contains the username, and letter is a char-value coming in. This works perfectly, except that I also want to get users that starts with digits. And I don't want to sort by separate digits.

My mind yells for a StartsWith("\d") but as far as I have found out it doesn't work this way. I have also thought of doing a 10-way OR clause, but that would look like spaghetti, and I'm not sure of the efficiency.

Is there any "right" way to do it like this?

like image 801
Christian Wattengård Avatar asked Apr 18 '11 11:04

Christian Wattengård


2 Answers

If this is for LINQ-to-SQL you could use SqlMethods.Like method here:

var result = repository
    .GetAll()
    .Where(q => SqlMethods.Like(q.BrukerIdent, "[0-9]%"))
    .ToList();
like image 144
Oleks Avatar answered Sep 19 '22 02:09

Oleks


repository.GetAll().Where(q => Char.IsNumber(q.BrukerIdent[0]))

MSDN


var numbers = Enumerable
                     .Range(0, 10)
                     .Select(i => i.ToString(CultureInfo.InvariantCulture));

// var numbers = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 );
// var numbers = HashSet<int> { ... };

var q = from b in repository.GetAll()
        where numbers.Contains(b.BrukerIdent.FirstOrDefault())) //[0]
        select b;
like image 43
abatishchev Avatar answered Sep 21 '22 02:09

abatishchev