Sort a List<T> using query expressions - LINQ C#
- by Dan Yack
I have a problem using Linq to order a structure like this :
public class Person
{
public int ID { get; set; }
public List<PersonAttribute> Attributes { get; set; }
}
public class PersonAttribute
{
public int ID { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
A person might go like this:
PersonAttribute Age = new PersonAttribute { ID = 8, Name = "Age", Value = "32" };
PersonAttribute FirstName = new PersonAttribute { ID = 9, Name = "FirstName", Value = "Rebecca" };
PersonAttribute LastName = new PersonAttribute { ID = 10, Name = "LastName", Value = "Johnson" };
PersonAttribute Gender = new PersonAttribute { ID = 11, Name = "Gender", Value = "Female" };
I would like to use LINQ projection to sort a list of persons ascending by the person attribute of my choice, for example, sort on Age, or sort on FirstName.
I am trying something like
string mySortAttribute = "Age"
PersonList.OrderBy(p => p.PersonAttribute.Find(s => s.Name == mySortAttribute).Value);
But the syntax is failing me. Any clues? Thanks in advance!