Home > C# Code Examples > C# Generic Lists

C# Generic Lists


using System;

using System.Collections.Generic;

using System.Text;

 

namespace Utilities

{

    class GenericList

    {

        public GenericList()

        {

            List<Person> people = new List<Person>();

 

            people.Add(new Person(50, “Fred”));

            people.Add(new Person(30, “John”));

            people.Add(new Person(26, “Andrew”));

            people.Add(new Person(24, “Xavier”));

            people.Add(new Person(5, “Mark”));

            people.Add(new Person(6, “Cameron”));

 

            // Unsorted list

            people.ForEach(delegate(Person p)

            {

                Console.WriteLine(String.Format(“{0} {1}”, p.age, p.name));

            });

 

            // Find

            List<Person> young = people.FindAll(delegate(Person p)

            {

                return p.age < 25;

            });

            young.ForEach(delegate(Person p)

            {

                Console.WriteLine(String.Format(“{0} {1}”, p.age, p.name));

            });

 

            // Sort by name

            people.Sort(delegate(Person p1, Person p2)

            {

                return p1.name.CompareTo(p2.name);

            });

            people.ForEach(delegate(Person p)

            {

                Console.WriteLine(String.Format(“{0} {1}”, p.age, p.name));

            });

 

            // Sort by age

            people.Sort(delegate(Person p1, Person p2)

            {

                return p1.age.CompareTo(p2.age);

            });

            Console.WriteLine(“Sorted list, by age”);

            people.ForEach(delegate(Person p)

            {

                Console.WriteLine(String.Format(“{0} {1}”, p.age, p.name));

            });

        }

    }

 

    public class Person

    {

        public int age;

        public string name;

 

        public Person(int age, string name)

        {

            this.age = age;

            this.name = name;

        }

    }

}

Advertisements
Categories: C# Code Examples
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: