Reputation: 801
How to create an Generic method for multiple tables? My tables :
I need to search for them with an Generic Method.I've tried the following:
Call:
var predicateSearchCustomer = GetSearchPredicate<Customer>(search,Types.Customer);
var predicateSearchEmployee = GetSearchPredicate<Employee>(search,Types.Employee);
My method:
public Expression<Func<T, bool>> GetSearchPredicate<T>(string parametrs, Types Types)
{
var predicateInner = PredicateBuilder.False<T>();
var paramertsForSearch = new List<string>(parametrs.Split(' '));
paramertsForSearch.RemoveAll(string.IsNullOrEmpty);
foreach (var item in paramertsForSearch)
{
var itemSearch = item;
switch (Types)
{
case Types.Customer:
predicateInner = predicateInner.Or(x => x.CustomerName.Contains(itemSearch));
predicateInner = predicateInner.Or(x => x.CustomerFamily.Contains(itemSearch));
break;
case Types.Employee:
predicateInner = predicateInner.Or(x => x.EmployeeName.Contains(itemSearch));
predicateInner = predicateInner.Or(x => x.EmployeeFamily.Contains(itemSearch));
break;
}
}
return predicateInner;
}
Error:
Error 5 'T' does not contain a definition for 'CustomerName' and no extension method 'CustomerName' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
How do I convert T
to Customer
or Employee
?
Upvotes: 0
Views: 384
Reputation: 43264
If you have to write a switch statement to do different things depending on the type passed to a generic method, then your method isn't generic. So write two methods. The code will be simpler to read (and will compile as an added bonus).
Having said that, your method here could be rewritten to be generic:
public Expression<Func<T, bool>> GetSearchPredicate<T>(string parameters,
Func<T, string, bool> test1,
Func<T, string, bool> test2)
{
var predicateInner = PredicateBuilder.False<T>();
var paramertsForSearch = new List<string>(parametrs.Split(' '));
paramertsForSearch.RemoveAll(string.IsNullOrEmpty);
foreach (var item in paramertsForSearch)
{
var itemSearch = item;
predicateInner = predicateInner.Or(x => test1(x, itemSearch));
predicateInner = predicateInner.Or(x => test2(x, itemSearch));
}
return predicateInner;
}
var predicateSearchCustomer =
GetSearchPredicate<Customer>(search,
(cust, term) => cust.CustomerName.Contains(term),
(cust, term) => cust.CustomerFamily.Contains(term));
var predicateSearchEmployee =
GetSearchPredicate<Employee>(search,
(empl, term) => empl.EmployeeName.Contains(term),
(cust, term) => empl.EmployeeFamily.Contains(term));
Upvotes: 2