Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print List of objects to Console

Tags:

c#

.net

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.

class Listobj
{
    int age;
    string name;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    static List<Listobj> newlist = new List<Listobj>();
    static void Main(string[] args)
    {
        /*newlist.Add(10);
        newlist.Add(2);
        newlist.Add(6);
        newlist.Sort();
        newlist.ForEach(Console.WriteLine);
        Console.ReadLine();*/
        Listobj obj = new Listobj();
        int tempage = 23;
        string tempname = "deepak";
        obj.Age = tempage;
        obj.Name = tempname;
        Listobj.newlist.Add(obj);
        foreach (Listobj item in newlist)
            Console.WriteLine(item);
        Console.ReadLine();
    }
}
like image 446
Deepak Rao Avatar asked Feb 07 '23 11:02

Deepak Rao


1 Answers

I would override ToString in your Listobj class.

public class Listobj
{
    private int age;
    private string name;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public override string ToString()
    {
        return "Person: " + Name + " " + Age;
    }
}

Then you can print like so:

foreach (var item in newlist.OrderBy(person => person.Age)) Console.WriteLine(item);
like image 181
d.moncada Avatar answered Feb 12 '23 10:02

d.moncada