Pass a func

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
					
public class Program
{
	public static void Main()
	{
		var models = new List<Model>{ new Model("01", 1, new Sortable("joking"))
			, new Model("Player", 5, new Sortable("man"))
			, new Model("Dream", 7, new Sortable("tux"))
			, new Model("Vanity", 6, new Sortable("apple"))};
		
		var collectionObj = new CollectionObj(){
			Models = models
		};
		
		//change this as needed to try different sorts
		collectionObj.OrderByDynamic(m => m.SortObj);
		
		foreach(var model in collectionObj.Models)
			Console.WriteLine("Id:{0, 10}, Value:{1, 3}, SortId:{2}", model.Id, model.Value, model.SortObj.SortId);
		
		
	}
}

public class CollectionObj {
	public IEnumerable<Model> Models {get; set;}

    public void OrderByDynamic(Func<Model, object> orderByFunc)
	{
		Models = Models.OrderBy(orderByFunc);
	}
	
}

public class Model {
	public string Id {get; set;}	
	public int Value {get; set;}
	public Sortable SortObj {get; set;}
	
	public Model(string id, int val, Sortable sortObj) {
		this.Id = id;
		this.Value = val;
		this.SortObj = sortObj;
	}
}

public class Sortable : IComparable 
{
	public string SortId {get; set;}
		
	public Sortable(string str)
	{
		this.SortId = str;
	}
	
	public int CompareTo(object other)
	{
		if (!(other is Sortable))
			throw new ArgumentException();
		
		return this.SortId.CompareTo(((Sortable) other).SortId);
	}
}
;