LINQ string[] against multiple fields

后端 未结 6 493
天命终不由人
天命终不由人 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:06

    Assuming that '\t' would never be part of the data you could do the following. You can of course substitute with any other character. With that assumption you could do as below:

    public static IEnumerable Where(this IEnumerable sequence, 
                                          string[] criteria){
    
    var properties = typeof(T).GetProperties()
                              .Where(p=>p.GetGetMethod() != null);
    return from s in sequence
           let text = properties.Aggregate("",(acc,prop) => 
                                                   acc + 
                                                   "\t" + 
                                                   prop.GetValue(s,null)
                                           )
           where criteria.All(c => text.Contains(c))
           select s;
    
    }
    

    EDIT I originally didn't include the usage since I found no collection in the original post but assuming the sequence is defined as IEnumerabl and can be accessed as a property called Persons on a variable db. the code would look similar to:

    IEnumerable persons = db.Persons.Where(criteria);
    

提交回复
热议问题