LINQ string[] against multiple fields

后端 未结 6 512
天命终不由人
天命终不由人 2021-01-02 20:59

Lets say I have a table dataContext.Customer with the following fields

    FName    varchar
    LName    varchar
    Phone    varchar
    DOB      datetime
          


        
6条回答
  •  我在风中等你
    2021-01-02 21:05

    I don't have a C# compiler at hand right now but I have this idea:

    Declare a lambda Expression like this:

    public Expression> GetFilterFromString(string input)
    {
        return p=> p.FName.Contains(input) ||
                   p.LName.Contains(input) ||
                   p.Phone.Contains(input) ||
                   p.DOB.ToString().Contains(input) ||
                   p.Address.Contains(input) ||    
    }
    

    Implementation may vary depending on your needs (like concatenating all fields, like you did with your SQL query).

    Then in your main query function:

    IQueryable customers = dataContext.Customers;
    foreach(string inputSearch in search)
    {
        customers = customers.Where(GetFilterFromString(inputSearch));
    }
    IEnumerable results = customers.AsEnumerable();
    

    I think the main advantage of this approach is that you have to declare GetFilterFromString once. Hope it is what you're looking for.

    Edit:

    Ok, so I read the SQL statement you were looking for (kind of late... but anyway). I think it's easy to adapt my solution. We will have to tweak the lambda expression a little:

    public Expression> GetFilterFromString(string input)
        {
            return p => (p.FName + " " +
                       p.LName + " " +                  
                       p.Phone + " " +
                       p.DOB.ToString() + " " +
                       p.Address)
                       .Contains(input) 
        }
    

提交回复
热议问题