Reputation: 111
I have a generic list which I want to order by two properties, priority and then by description to fill a drop down list.
I know that when I now exactly the type of the object list I can do
list = list.Orderby(x=>x.property1).ThenOrderBy(x=>x.property2).
My question is how can I check if the property1 and property2 exist on the object and then sort my list based on those properties.
Upvotes: 1
Views: 1208
Reputation: 547
well, the way you are trying to do it is a bad idea. Try using if-else or switch case first and then put your code to order them the way you want accordingly.
Upvotes: 0
Reputation: 14477
You can wrap the selector in a try-catch
block :
Func<dynamic, dynamic> DynamicProperty(Func<dynamic, dynamic> selector)
{
return x =>
{
try
{
return selector(x);
}
catch (RuntimeBinderException)
{
return null;
}
};
}
Usage :
var sorted = list
.OrderBy(DynamicProperty(x => x.property1))
.ThenBy(DynamicProperty(x => x.property2));
Upvotes: 0
Reputation: 833
Because you are using a generic list, the compiler will check that for you.
For example: if you write code like
List<Object> list = new List<Object>();
var newlist = list.Orderby(x=>x.property1).ThenOrderBy(x=>x.property2);
you'll get a compiler error on property1 & property2 because the compiler won't find these properties on the Object type.
If you want to support different types that each should have those 2 properties, the correct way would be to create an interface with those 2 properties, let each of the types you want to support implement that interface and then use a constraint on T like Arturo proposed.
Something like
interface ICanBeSorted
{
string property1 {get;}
string property2 {get;
}
public List<T> MySortMethod(List<T> list) where T : ICanBeSorted
{
return list.OrderBy(x=>x.property1).ThenOrderBy(x=>x.property2);
}
This method will be able to sort all types that implement interface ICanBeSorted.
Upvotes: 2