Charmandir
Charmandir

Reputation: 13

Linq Query filtering results

I'm not super familiar with LINQ. Here's some code:

if (!String.IsNullOrEmpty(searchString))
            {
                games = games.Where(x => x.Name.Contains(searchString));
            }

Works as it should; however, what I'd like, rather than filtering results based on whatever text the user inputs, if the user inputs say "L" is there a way within the LINQ query to have it filter through the 1st letters of x.Name verses any x.Name that contains the letter.

I.E. say I have...

League_of_Legends
LOTRO_
Dota_2
Call_of_Duty_4
Final_Fantasy_7

And the user inputs "L" rather than returning all but Dota 2, can it return only League of Legends and LOTRO as they are the only two who's names actually start with "L".

I'm assuming its something along the lines of... games = games.Where(x => x.Name.Contains<***something***>(searchString));

Thanks!

Upvotes: 0

Views: 81

Answers (1)

Douglas
Douglas

Reputation: 54917

I assume you're looking for StartsWith. Note that this will work for any prefix, not just a single letter.

games = games.Where(x => x.Name.StartsWith(searchString));

If you want a case-insensitive search (e.g. where lowercase l matches League_of_Legends too), use:

games = games.Where(x => x.Name.StartsWith(searchString, StringComparison.CurrentCultureIgnoreCase));

Upvotes: 3

Related Questions