valerii.sverdlik
valerii.sverdlik

Reputation: 559

How to use predicate search with Linq-to-SQL

We are using Linq-to-SQL with SQL Server as an ORM on our new project. I have never used Linq-to-SQL before, so my question can be a bit dumb. I want to have a method that will perform a search for entities in DB by predicate, something like this:

public IEnumerable<T> Get<T>(Expression<Func<T, bool>> @where)

Could you give some advices where I can see some code samples or ideas how to implement this?

Upvotes: 0

Views: 92

Answers (1)

Evren Kuzucuoglu
Evren Kuzucuoglu

Reputation: 3885

You want Where (here, originalList is any enumerable, in particular it can be a table from your context):

var filteredList = originalList.Where(element => ShouldBeIncluded(element));

Edit:

or

var filteredList =
    from element in originalList
    where ShouldBeIncluded(element)
    select element;

And if ShouldBeIncluded is a Func<T, bool>, there's an eye-candy simplified syntax:

var filteredList = originalList.Where(ShouldBeIncluded);

Edit 2: also, note that the complete syntax is:

var filteredList = originalList.Where<TTypeOfElement>(element => ShouldBeIncluded(element));

But the generic argument can be omitted since the compiler will deduce it from the type of originalList (supposing it is an IEnumerable<TTypeOfelement>).

Upvotes: 1

Related Questions