by pietman
17. February 2011 09:19
public class TypedProperty<T> : Property
{
public T TypedValue
{
get { return (T)Convert.ChangeType(base.Value, typeof(T)); }
set { base.Value = value.ToString();}
}
}
8824c6b1-a574-4a47-a3a5-c3c0f42c3141|0|.0
Tags:
c# | Generics
by pietman
6. October 2010 12:13
using System;
using System.Collections.Generic;
public class Person
{
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
public string name ;
public int age;
}
public class MyClass
{
public static void Main()
{
List<Person> Plist = new List<Person>();
Plist.Add(new Person("Mike", 35));
Plist.Add(new Person("Andy",50));
Plist.Add(new Person("Louis",60));
Plist.Add(new Person("John",22));
Console.WriteLine("********* unsorted *******************");
foreach(Person p in Plist)
Console.WriteLine(p.name + " ," + p.age.ToString());
Console.WriteLine("********* sorted by age *************");
//lambda expression
Plist.Sort((Person a,Person b) => a.age.CompareTo(b.age) );
Plist.ForEach(delegate(Person p) {
Console.WriteLine(p.name + " ," + p.age.ToString());});
Console.WriteLine("********* sorted by name ************");
//delegate
Plist.Sort(delegate(Person a,Person b) { return a.name.CompareTo(b.name); });
Plist.ForEach((Person p) => Console.WriteLine(p.name + " ," + p.age.ToString()));
Console.WriteLine("*************************************");
Console.WriteLine("... press any key");
Console.ReadKey();
}
}
Output:
********* unsorted *******************
Mike ,35
Andy ,50
Louis ,60
John ,22
********* sorted by age *************
John ,22
Mike ,35
Andy ,50
Louis ,60
********* sorted by name ************
Andy ,50
John ,22
Louis ,60
Mike ,35
*************************************
... press any key
8a4c3392-bfbf-4aa5-b02d-41c63d7b0cc2|0|.0
Tags:
c# | Generics
by pietman
25. November 2009 13:14
This is a simple example of how to sort a Generic List List(T)
using System;
using System.Collections.Generic;
public class MySortExample
{
private static int CompareVehiclesByWeight(Vehicle x, Vehicle y)
{
if ((x == null) && (y == null))
return 0;
if ((x == null) && (y != null))
return -1;
if ((x != null) && (y == null))
return 1;
return (x.Weight.CompareTo(y.Weight));
}
public static void Main()
{
List<Vehicle> Vehicles = new List<Vehicle>();
Console.WriteLine("\nCapacity: {0}", Vehicles.Capacity);
Vehicles.Add(VehicleType.Car);
Vehicles.Add(VehicleType.Bicycle);
Vehicles.Add(VehicleType.Plane);
Vehicles.Add(VehicleType.Ship);
Vehicles.Add(VehicleType.Motorbike);
Vehicles.Sort(CompareVehiclesByWeight);
}
}
You can created multiple sorting algorithms, sorting on different elements/fields and then just call the sort method that you want to use at the appropriate time.
4ff30b66-3faa-4e10-a4c4-ae93139c69c5|0|.0
Tags:
c# | Generics