Showing posts with label sort items. Show all posts
Showing posts with label sort items. Show all posts

Tuesday, September 22, 2009

How to find an element in c# Generic List

The following sample code demonstrates you how to find a matching element in the object list.

Let's say we have an object called Person with public properties PersonID, Name, Age, Gender as defined below.

using System.Collections.Generic.List;

public class Person
{
public int PersonID {get; set;}
public string Name {get; set;}
public int Age {get; set;}
public bool Gender {get; set;}
}

class program
{
public static void Main(string[] args)
{
// Let's say we have a method defined as dbAccess.GetPersons() to
//return all the records from Person table and populates the
//list object "persons" as shown below.
List persons = dbAccess.GetPersons();

int personIDToFind = 1234;
//Find person in persons list by PersonID using predicate
//"p=>p.PersonID == personIDToFind"
Person personByFindOperation = persons.Find( p=>p.PersonID == personIDToFind );

string personName = "Kiran"
//Find person in persons list by Name using predicate
//"p=>p.Name == personName"
Person personByFindOperation2 = persons.Find( p=>p.Name == personName );

}
}

Note: The Find method of List returns the first occurrence of the exact match within the entire System.Collections.Generic.List.


kick it on DotNetKicks.com
Shout it

Tuesday, April 28, 2009

How to sort list of objects in C#

The following code helps in sorting list of objects based on some property’s value.

public class Person
{
public int age;
public string name;

public Person(int age, string name)
{
this.age = age;
this.name = name;
}
}

List people = new List();

people.Add(new Person(50, “Kiran”));
people.Add(new Person(30, “Raghava”));
people.Add(new Person(26, “Andrew”));
people.Add(new Person(24, “Praveen”));
people.Add(new Person(5, “Sudhir”));
people.Add(new Person(6, “Prudhvi”));

Console.WriteLine(”Unsorted list”);
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format(”{0} {1}”, p.age, p.name)); });

Console.WriteLine(”Sorted list, 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)); });

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