G
G
GetB2015-01-10 13:45:49
.NET
GetB, 2015-01-10 13:45:49

How would you implement filtering on multiple fields in Entity Framework?

There is a filter like this:

return DbSet.Where(u => u.FirstName.IndexOf(search) > -1
                                    || u.LastName.IndexOf(search) > -1
                                    || u.UserName.IndexOf(search) > -1
                                    || u.Email.IndexOf(search) > -1);

Using the entered search word, the data is filtered.
Now I want to remake the algorithm in such a way that you can enter two words (Email LastName) and the data is already filtered based on two parameters. And the more parameters, the more accurate the filtering, i.e. as a result, one record that satisfies the condition may remain in the final table.
The idea was to do this:
return DbSet.Where(u => u.FirstName.IndexOf("WORDS ARRAY")) > -1
                                        || u.LastName.IndexOf("WORDS ARRAY") > -1
                                        || u.UserName.IndexOf("WORDS ARRAY") > -1
                                        || u.Email.IndexOf("WORDS ARRAY") > -1);

those. instead of WORD ARRAY, an array of words is passed and each parameter must choose the word that suits it for filtering, but it still doesn’t work out.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Nemiro, 2015-01-10
@AlekseyNemiro

For array search - Array.IndexOf . I won’t say for sure if it will work in LINQ , I wouldn’t do it myself with data from the database. SQL is our everything :)

string[] arr = {"слово 1", "слово 2"};
return DbSet.Where(u => Array.IndexOf(arr, u.FirstName) != -1);

Another option, worse, but with the ability to ignore case:
string[] arr = {"слово 1", "слово 2"};
return DbSet.Where(u => arr.Any(itm=> itm == u.FirstName));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question