Useful article on sorting generic lists with nested types using LINQ

HelperĀ  method for sorting generic lists with nested types using LINQ

 public static class Comparer 
 { 
 public static List<T> Sort<T>(List<T> listToBeSorted, string sortBasePropertyName, SortDirection sortDirection) 
 { 
 IOrderedEnumerable<T> result; 
 if (!string.IsNullOrEmpty(sortBasePropertyName)) 
 { 
 if (sortDirection == SortDirection.Ascending) 
 { 
 result = from i in listToBeSorted 
 orderby GetSortBaseProperty(i, sortBasePropertyName) 
 select i; 
 } 
 else 
 { 
 result = from i in listToBeSorted 
 orderby GetSortBaseProperty(i, sortBasePropertyName) descending 
 select i; 
 } 
 return result.ToList(); 
 } 
 else 
 { 
 return listToBeSorted; 
 } 
 } 
 public static object GetSortBaseProperty(object o, string SortBasePropertyName) 
 { 
 if (SortBasePropertyName.Contains('.')) 
 { 
 int dotIndex = SortBasePropertyName.IndexOf(".") + 1; 
 object top1Prop = o.GetType().InvokeMember(SortBasePropertyName.Split('.')[0], BindingFlags.GetProperty, null, o, null); 
 return GetSortBaseProperty(top1Prop, SortBasePropertyName.Substring(dotIndex, SortBasePropertyName.Length - dotIndex)); 
 } 
 else 
 { 
 return o.GetType().InvokeMember(SortBasePropertyName, BindingFlags.GetProperty, null, o, null); 
 } 
 } 
 } 

Cheers and happy coding

K.Anantha rengan


My first blogpost in wordpress

Hello everyone

Welcome to my blog

 

Follow

Get every new post delivered to your Inbox.