I am working on the search using LINQ in C#.
Basically in SQL, it is
SELECT *
FROM myDB
WHERE searchTerm IN (col1, col2, . . . );
As I cannot find a way to do it in LINQ, this is what I did.
var v = (from item in myDB
where item.COL1.Contains(searchTerm)
|| item.COL2.Contains(searchTerm)
|| item.COL3.Contains(searchTerm)
...
select item);
Is there smarter way to do it?
CodePudding user response:
The equivalent of your SQL code would be:
from item in myDB
where item.COL1 == searchTerm
|| item.COL2 == searchTerm
|| item.COL3 == searchTerm
...
select item
Or:
myDB.Where(item => item.COL1 == searchTerm
|| item.COL2 == searchTerm
|| item.COL3 == searchTerm
...)
Since you're working with a finite and hard-coded list of columns, it's probably fine leaving a little repetition in the code this way. If you needed the list of columns to be dynamic, you could build a list of criteria and use code like this to "OR" those criteria together.