Sort a List using query expressions

后端 未结 7 682
执念已碎
执念已碎 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:08

    This is assuming that Attribute class implement IComparable or has a nice ToString function (i hope).

    var list = personList.OrderBy(p => p.Attributes.FirstOrDefault(a => a.Name == "Age"))
    

    Otherwise the syntax gets more convoluted:

    var list = personList
                .OrderBy(p => 
                         p.Attributes.FirstOrDefault(a => a.Name == "Age") == null ?
                         "" : p.Attributes.First(a => a.Name == "Age").Value
                );
    

    I also assume that you have one value for each key - otherwise you'd need to have smarter code... ;-)

提交回复
热议问题