Deepak Rao
Deepak Rao

Reputation: 103

Print List of objects to Console

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

Upvotes: 7

Views: 39674

Answers (3)

Thomas Ayoub
Thomas Ayoub

Reputation: 29481

You can use Linq to order your list:

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

Also, a few improvements:

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

Upvotes: 3

shd
shd

Reputation: 1

You can do with using the IEnumerable varaible, and then sorting them in ascending order using linq

IEnumerable<Listobj> temp = newlist;
temp = from v in temp
       orderby v.age ascending
       select v;

foreach (Listobj item in temp)
{
    Console.WriteLine(item.Name +"with the age"+ item.Age);
}

Console.ReadLine();

Upvotes: -1

d.moncada
d.moncada

Reputation: 17402

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

Upvotes: 7

Related Questions