Sort a List using query expressions

后端 未结 7 667
执念已碎
执念已碎 2021-02-05 15:34

I have a problem using Linq to order a structure like this :

public class Person
{
    public int ID { get; set; }
    public List Attribu         


        
7条回答
  •  独厮守ぢ
    2021-02-05 16:04

    Some cases you need to consider:

    • Since your attribute is in string an age of "30" and "3" will be ordered before an age of "4"
    • The attribute might not exist

    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);
    

提交回复
热议问题