Pinball125
Pinball125

Reputation: 25

LINQ where clause using Generic IQueryable source

I'm trying to make a method that will filter through an IQueryable datasource with a generic type. I want to have a search method that I could reuse for each of the tables that I will be creating. Preferably I would like to be able to pass a field type as well into this so that I can narrow the search, but also wouldn't care if it just looked into every field.

So far I have this:

public static IQueryable<T> Search<T>(IQueryable<T> dataSource, string searchFor)
{
    foreach(var variable in dataSource) 
    {
        dataSource = dataSource.Where(var.Contains(searchFor));
    }
}

i don't know if this really possible, but it would save me a ton of coding since I will have to implement a new search method for each new table that I would be viewing.

Upvotes: 1

Views: 347

Answers (1)

Samvel Petrosov
Samvel Petrosov

Reputation: 7706

You don't need for loop here and have mistake in this line:

dataSource = dataSource.Where(var.Contains(searchFor));

You can define interface in this way:

public interface IMyInterface
{
    bool Contains(string searchFor);
}

and now you can write your function in the following way:

public static IQueryable<T> Search<T>(IQueryable<T> dataSource, string searchFor) where T:IMyInterface
{

    return dataSource.Where(x=>x.Contains(searchFor));
}

Upvotes: 1

Related Questions