Pedro
Pedro

Reputation: 238

How to make a query with the filter in a generic list?

I have the generic object T.

I want to do query informing the properties just like I do in SQL with the logical operator or "OR column1 = 123" or "OR column2 = 123"

public ActionResult Result<T>(HttpContext httpContext, IQueryable<T> queryable, string[] columns = null)
{
    var entity = queryable;
    string searchValue = "123";

    if (!string.IsNullOrEmpty(searchValue))
    {
        entity = entity.Where(""); // columns              
        ...
    }
}

Upvotes: 0

Views: 401

Answers (2)

koryakinp
koryakinp

Reputation: 4125

If you have entities

class Foo {
    public string BazFoo { get; set; }
}

class Bar {
    public string BazBar { get; set; }
}

You can create an Interface:

public interface IBaz
{
    string GetBaz();
}

And implement it by your entities:

class Foo : IBaz
{
    public string BazFoo { get; set; }
    public string GetBaz() => BazFoo;
}

class Bar : IBaz
{
    public string BazBar { get; set; }
    public string GetBaz() => BazBar;
}

And you can use it in a following way:

if (!string.IsNullOrEmpty(searchValue))
{
    entity = queryable.Where(_ => _.GetBaz() == searchValue);
    ...
}

Upvotes: 0

Igor
Igor

Reputation: 62213

You could apply an interface constraint but honestly I would just as soon not do that if I were you because it could lead to code that is more difficult to read and maintain.

public interface ICommonEntity
{
    string Column1 { get; }
    string Column2 { get; }
}

Make any applicable type implement the above interface

public ActionResult Result<T>(HttpContext httpContext, IQueryable<T> queryable, string[] columns = null) where T : class, ICommonEntity
{
    var entity = queryable;
    string searchValue = "123";

    if (!string.IsNullOrEmpty(searchValue))
    {
        entity = entity.Where(_ => _.Column1 == searchValue || _.Column2 == searchValue);
        ...
    }
}

Upvotes: 1

Related Questions