Dynamic LINQ: Use .NET Contains method to generate a dynamic search method

dynamic-linq linq

Question

I have a class Item like

public class Item
{
   public int Id {get;set;}
   public string Name {get;set;}
   public string PartialDescription {get;set;}
   public string FullDescription {get;set;} 
   public doulbe Price {get;set;}
}

I would like to have a dynamic custom query method SearchOverAnyFields() that can accept any number of Item object's properties like:

// key is an input string variable

// one query 
var results = myItems.SearchOverAnyFields(x => x.Name.Contains(key) || x.PartialDescription.Contains(key) || x.Price.ToString().Contains(key));

// or another query 
var results2 = myItems.SearchOverAnyFields(x => x.Name.Contains(key) || x.PartialDescription.Contains(key) || x.Price.ToString().Contains(key) 
|| x.FullDescription.Contains(key));

// or another query
var results3 = myItems.SearchOverAnyFields(x => x.PartialDescription.Contains(key) ||  x.FullDescription.Contains(key));

Please help.

1
1
2/21/2012 4:49:05 PM

Popular Answer

I'm not really sure what you're looking for here - the functionality you want can be easily achieved with the Where operator.

var results = myItems.Where(x => x.Name.Contains(key) || 
    x.PartialDescription.Contains(key) || x.Price.ToString().Contains(key));

// or another query 
var results2 = myItems.Where(x => x.Name.Contains(key) || 
    x.PartialDescription.Contains(key) || x.Price.ToString().Contains(key) 
    || x.FullDescription.Contains(key));

// or another query
var results3 = myItems.Where(x => x.PartialDescription.Contains(key) ||  
    x.FullDescription.Contains(key));

Does this meet your requirement?

1
2/22/2012 1:02:42 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow