Reputation: 2629
I have the following classes:
public class Vehicle
{
public string Name { get; set; }
public bool CanFly { get; set; }
public bool CanDive { get; set; }
}
public class Hdd
{
public string Name { get; set; }
public bool CanRead { get; set; }
public bool CanWrite { get; set; }
public bool CanCopy { get; set; }
}
I want to write one function that can filter for example if a specific car exists (filter by firstOrDefault name) then check the given condition as parameter, for example CanFly or CanDive... etc
so i was thinking of:
public class TestProperties
{
public bool Check<T>(List<T> items, string name,
Expression<Func<T, bool>> expression)
{
var expr = (MemberExpression)expression.Body;
var prop = (PropertyInfo)expression.Member;
//1- Filter items with the given name
// return false if no records found
// return false if the condition fails
}
}
Then I would call the functions as follow
var myHdds= GetHdd();
var myCars= GetCars();
var CanRead = Check<Hdd>(myHdds,"samsung",x => x.CanRead);
var CanFly = Check<Vehicle>(myCars,"Audi",x => x.CanFly);
How can i implement the Check function?
Upvotes: 2
Views: 57
Reputation: 6430
You are almost there. Try this -
public bool Check<T>(List<T> items, Expression<Func<T, bool>> expression)
{
return items.Any(x => expression.Compile()(x));
}
or,
public bool Check<T>(List<T> items, Func<T, bool> compiledExp)
{
return items.Any(x => compiledExp(x));
}
and call like this -
Check<Vehicle>(myCars, x => x.Name == "Audi" && x.CanFly);
Check<Hdd>(myHdds,x => x.Name == "Samsung" && x.CanRead);
But now to think of this, you really don't need a method to do that. It is literally one line of code.
Personally I would have preferred an extension method -
public static bool Check<T>(this List<T> items, Func<T, bool> compiledExp)
{
return items.Any(x => compiledExp(x));
}
and call like -
myHdds.Check(x => x.Name == "Samsung" && x.CanRead);
Upvotes: 2