LINQ to SQL query to determine if value starts with numeric

后端 未结 4 1615
[愿得一人]
[愿得一人] 2020-12-11 20:18

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

repository.GetAll().Where(q => q.BrukerIdent.StartsWith(letter.ToString())).ToList();
相关标签:
4条回答
  • 2020-12-11 20:47

    I suspect @abatishchev's revised answer will help here, but if you are doing this lots, or this is an important query, then I strongly suggest a refactor. For example:

    create table Test (
        id int not null identity(1,1) primary key clustered,
        name nvarchar(20) not null,
        firstChar as (case when LEN(name) = 0 then null
                else SUBSTRING(name,1,1) end) persisted
        )
    go
    create nonclustered index Test_firstChar on Test (firstChar)
    

    I can now do a very efficient first-character match simply by testing firstChar. Which could be an integer instead if the numeric ones are particularly important.

    0 讨论(0)
  • 2020-12-11 20:53

    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();
    
    0 讨论(0)
  • 2020-12-11 20:56

    Perhaps not so readable, but the following would probably work:

    q.BrukerIdent >= "0" && q.BrukerIdent < ":"
    

    Maybe there are some exotic collation sequences where this would fail, but I expect it would work in most situations.

    0 讨论(0)
  • 2020-12-11 21:03
    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;
    
    0 讨论(0)
提交回复
热议问题