Avatar ·

Dynamic LINQ sorting: how to apply OrderBy to IEnumerable/IQueryable by property name from a string?

Hello everyone! I'm new to C# and LINQ, and I've encountered a task that has me stumped.\n\nI have a collection of `IEnumerable` (or `IQueryable`) objects, and I want to sort it by different fields depending on user selection. The user passes the field name (e.g., "Name" or "Date") and sort direction ("asc" or "desc") as strings. How can I dynamically apply `OrderBy` or `OrderByDescending` to the collection using these strings?\n\nThe problem is that `OrderBy` is a generic method that requires specifying the property at compile time via a lambda expression (e.g., `list.OrderBy(x => x.Name)`). I can't just write `list.OrderBy("Name")`.\n\nHere's an example of code that doesn't work:\n\n```csharp\npublic List SortPeople(IEnumerable people, str