Reputation: 221
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.
Upvotes: 1
Views: 486
Reputation: 856
Something like this would probably do the job for you...
public static IEnumerable<Item> SearchOverAnyFields(this IEnumerable<Item> items, string key, params Func<Item,string>[] fields)
{
return
from item in items
from field in fields.
Where(field => field(item) != null && field(item).Contains(key))
select item;
}
public static void ExampleUsage(object[] args)
{
var items = new List<Item> { new Item { Name = "badger" }, new Item { PartialDescription = "badger" }, new Item { } };
// searches items for any item that has "badger" in it's name or PartialDescription
var result = items.SearchOverAnyFields("badger", i => i.Name, i => i.PartialDescription);
foreach (var res in result)
Debug.WriteLine(res);
}
Calling ExampleUsage() would print two statements to the debug console, to verify they're the correct Items you'd have to build a ToString method for them.
Upvotes: 1
Reputation: 28738
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?
Upvotes: 1