score:2

Accepted answer

You can put that choice in a conditional statement:

IQueryable<Whatever> query = ...;

if (searchText.StartsWith("^"))
{
    query = query.Where(w => w.English.StartsWith(searchText.Substring(1)));
}
else
{
    query = query.Where(w => w.English.Contains(searchText));
}

You can also do the same comparison inline, but that'll generate very ugly SQL, if it even works:

query = query.Where(w => 
        searchText.StartsWith("^")
            ? w.English.StartsWith(searchText.Substring(1))
            : w.English.Contains(searchText));

Do note that you generally don't want to search text using SQL, as that results in a pretty poor user experience. Take a look at full-text indexing.

score:1

if (options.English != null) 
{
    bool englishStartsWith = options.English.StartsWith("^");
    if(englishStartsWith)
    {
       query = query.Where(w => w.English.StartsWith(options.English.Substring(1)));
    }
    else
    {
       query = query.Where(w => w.English.Contains(options.English));
    }
}

score:3

Assuming that you're using Entity Framework, you can use the StartsWith() and EndsWith() methods, to achieve the same results as Contains() except only at the beginning or the end of a string. It will generate the code for you.

Then simply create conditional statements in your code, in order to determine which one of the methods you should use.

Some word of advice:

There might be a bug with EF Core, in which it turns StartsWith("string") into LIKE "string%" which might yield incorrect results with strings, containing wildcard characters such as "_".

So I'd advise you to use plain SQL with EF Core, and given that you're using SQL Server as a DBMS, query like that:

if (searchText.StartsWith("^"))
{
    var result = query.FromSql($"SELECT something FROM table WHERE PATINDEX({searchText.Substring(1)}, something) = 1");
}
else
{
    var result = query.FromSql($"SELECT * FROM table WHERE PATINDEX({searchText.Substring(1)}, something ) <> 0");
}

With PATINDEX() you will get correct results even if your pattern string contains wildcard characters - escaping potential bugs with relying on StartsWith() and EndsWith() to generate proper SQL code.

But that's only for EF Core, EF 6 works like a charm the way other people answered :)


Related Query

More Query from same tag