Sort a List<T> using query expressions - LINQ C#

Posted by Dan Yack on Stack Overflow See other posts from Stack Overflow or by Dan Yack
Published on 2009-03-30T03:18:07Z Indexed on 2010/04/22 15:33 UTC
Read the original article Hit count: 322

Filed under:
|
|
|
|

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!

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about c#