Print List of objects to Console

后端 未结 3 1295
刺人心
刺人心 2020-12-03 19:35

I created a list with Listobj object type. And added a set of values to the object.

How do I print the Listobj objects from the newlist in an increasing age fashion.

3条回答
  •  悲&欢浪女
    2020-12-03 20:18

    You can use Linq to order your list:

    foreach (Listobj item in newlist.OrderBy(x => x.Age))
        Console.WriteLine(item);
    

    Also, a few improvements:

    • You should override ToString()
    • Use Auto-Implemented Properties

    Which gives:

    public class Listobj
    {
        public int Age { get; set; }
        public string Name { get; set; }
    
        public override string ToString()
        {
            return string.Format("My name is {0} and I'm {1} years old.", Name, Age);
        }
    }
    

提交回复
热议问题