.

Generic Random / Shuffle extention method for Lists etc.

This will allow you to shuffle and Ilist / List etc.

public static class RandomExtension
{
    private static Random rng = new Random();

    public static void Shuffle<T>(this IList<T> list)
    {
        int n = list.Count;
        while (n > 1)
        {
            n--;
            int k = rng.Next(n + 1);
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }
}

Another neat “trick” to do so is:

var shuffledcards = cards.OrderBy(a => Guid.NewGuid());

Dictionary Serializer

The Dictionary class itself is not serializable, so we create a class SerializableDictionary and derive from Dictionary as well as the interface IXmlSerializable
in order to make a Serializable Dictionary.

[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
    #region IXmlSerializable Members

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof (TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof (TValue));
        bool wasEmpty = reader.IsEmptyElement;
        reader.Read();
        if (wasEmpty) return;
        while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
        {
            reader.ReadStartElement("item");
            reader.ReadStartElement("key");
            TKey key = (TKey) keySerializer.Deserialize(reader);
            reader.ReadEndElement();
            reader.ReadStartElement("value");
            TValue value = (TValue) valueSerializer.Deserialize(reader);
            reader.ReadEndElement();
            this.Add(key, value);
            reader.ReadEndElement();
            reader.MoveToContent();
        }
        reader.ReadEndElement();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof (TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof (TValue));
        foreach (TKey key in this.Keys)
        {
            writer.WriteStartElement("item");
            writer.WriteStartElement("key");
            keySerializer.Serialize(writer, key);
            writer.WriteEndElement();
            writer.WriteStartElement("value");
            TValue value = this[key];
            valueSerializer.Serialize(writer, value);
            writer.WriteEndElement();
            writer.WriteEndElement();
        }
    }

    #endregion
}

Generic Enum parser

public static class MyExtensions
{
    public static TEnum ParseEnum&lt;TEnum&gt;(this string value,
        bool ignoreCase = false) where TEnum : struct
    {
        TEnum tenumResult;
        Enum.TryParse&lt;TEnum&gt;(value, ignoreCase, out tenumResult);
        return tenumResult;
    }
}

usage: 
var enumValue = "One".ParseEnum<EnumOne>();

converting values to the generic type

 

 

public class TypedProperty<T> : Property 
{ 
 public T TypedValue 
 { 
   get { return (T)Convert.ChangeType(base.Value, typeof(T)); } 
   set { base.Value = value.ToString();} 
 } 
}


 

sorting lists using delegates / lambda expressions

 

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

List.Sort made simple

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.

generic list inline sorting using delegates

 an example of how to use an inline sort function with a delegate to define the sort process 

public static List<Container.Speciality> getSpecialties()
{
    Kingsweb2DataAccess.Kingsweb2DataClassesDataContext newdb =
        new Kingsweb2DataAccess.Kingsweb2DataClassesDataContext();

    List<Container.Speciality> res =
        new List<Kingsweb2DataAccess.Container.Speciality>();
    var x = from m in newdb.specialities select m;
    foreach (Kingsweb2DataAccess.speciality xx in x)
    {
        res.Add(new Kingsweb2DataAccess.Container.Speciality(xx.Id));
    }

    res.Sort(delegate(Kingsweb2DataAccess.Container.Speciality a,
        Kingsweb2DataAccess.Container.Speciality b)
            { return a.Specialityname.CompareTo(b.Specialityname); });

    return res;
}