I have a problem using Linq to order a structure like this :
public class Person
{
public int ID { get; set; }
public List Attribu
Some cases you need to consider:
If you create this extension methods class:
public static class ListExtenstions
{
public static List OrderList(this List list, string attributeName, PersonAttribute defaultAttribute)
{
return OrderList(list, attributeName, defaultAttribute, x => x);
}
public static List OrderList(this List list, string attributeName, PersonAttribute defaultAttribute, Func convertion)
{
return list.OrderBy(x => convertion((x.Attributes.FirstOrDefault(y => y.Name == attributeName) ?? defaultAttribute).Value)).ToList();
// Query Syntax
//return
// (from p in list
// let attribute = p.Attributes.FirstOrDefault(a => a.Name == attributeName) ?? defaultAttribute
// orderby attribute.Value
// select p).ToList();
}
}
You can then sort the list correctly in this manner:
List persons = ...
...
PersonAttribute defaultAttribute = new PersonAttribute() { Value = "0" };
var ordered = persons.OrderList("Age", defaultAttribute, x => Convert.ToInt32(x));
This will give correct sorting order.
If the attribute will always be present you could remove defaultAttribute
.
To sort on 'Name' just use:
List persons = ...
...
PersonAttribute defaultAttribute = new PersonAttribute() { Value = String.Empty };
var ordered persons.OrderList("Name", defaultAttribute);