Sort a List using query expressions

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

    I'd imagine that you're getting an exception where one item doesn't have an age attribute. I tried the below code, and it worked fine - I'm guessing your data is a bit off, as pointed out by other posters. Anyway, the below works fine...

        List personList = new List();
        Random rand = new Random();
    
        //generate 50 random persons
        for (int i = 0; i < 50; i++)
        {
            Person p = new Person();
            p.Attributes = new List();
            p.Attributes.Add(new PersonAttribute() { ID = 8, Name = "Age", Value = rand.Next(0, 100).ToString() });
            p.Attributes.Add(new PersonAttribute() { ID = 10, Name = "Name", Value = rand.Next(0, 100).ToString() });
            personList.Add(p);
        }
    
        var finalList = personList.OrderBy(c => c.Attributes.Find(a => a.Name == "Age").Value).ToList();
    

提交回复
热议问题