Here you can see it in practice, given
List<MyClass> list;
and
public class MyClass
{
public string Name { get; set; }
}
you can say
list.OrderBy(x => x.Name);
this IEnumerable<TElement> source is how we know that we call it as an extension method by any IEnumerable.
, . , , . , , :
public object GetPropertyByName(object obj, string propertyName)
{
object result = null;
var prop = obj.GetType().GetProperty(propertyName);
result = prop.GetValue(obj, null);
return result;
}
:
List<MyClass> list = new List<MyClass>();
list.Add(new MyClass { Name = "John" });
list.Add(new MyClass { Name = "David" });
list.Add(new MyClass { Name = "Adam" });
list.Add(new MyClass { Name = "Barry" });
const string desiredProperty = "Name";
var result = list.OrderBy(x => GetPropertyByName(x, desiredProperty));
foreach (MyClass c in result)
{
Console.WriteLine(c.Name);
}