Note that there are some explanatory texts on larger screens.

plurals
  1. POSort List<T> using string without Linq
    primarykey
    data
    text
    <p>Is there a way to sort a <code>List&lt;T&gt;</code> using a string like <code>"Name desc"</code> (same as <code>DataTable.DefaultView.Sort</code>) rather then Linq?</p> <p>I'm trying to replace <code>DataTables</code> with <code>Lists</code> and I need it to do this to be compatible with old code.</p> <p><strong>SOLUTION</strong></p> <p>using V4Vendetta's code I was able to create this extension method, tests seem to show it working.</p> <pre><code>public static void SortByString&lt;T&gt;(this List&lt;T&gt; list, string sortString) { if (sortString == null) return; List&lt;string&gt; SortGroups = sortString.Split(',').ToList(); for (int i = SortGroups.Count - 1; i &gt;= 0; i--)// sort from the last group first { string tempColumn = SortGroups[i].Trim().Split(' ')[0]; bool isAsc = SortGroups[i].Trim().Split(' ').Length &gt; 1 ? SortGroups[i].Trim().Split(' ')[1].ToLower() == "asc" ? true : false : true; PropertyInfo propInfo = typeof(T).GetProperty(tempColumn); if (propInfo == null) // if null check to make sure its not just a casing issue. { foreach (PropertyInfo pi in typeof(T).GetProperties()) { if(pi.Name.ToLower() == tempColumn.ToLower()) { tempColumn = pi.Name; propInfo = typeof(T).GetProperty(tempColumn); break; } } } if (propInfo != null) { Comparison&lt;T&gt; compare = delegate(T a, T b) { object valueA = isAsc ? propInfo.GetValue(a, null) : propInfo.GetValue(b, null); object valueB = isAsc ? propInfo.GetValue(b, null) : propInfo.GetValue(a, null); return valueA is IComparable ? ((IComparable)valueA).CompareTo(valueB) : 0; }; list.Sort(compare); }else{ throw new IndexOutOfRangeException("Property: '" + tempColumn + "', does not exist in '" + typeof(T).ToString() + "'"); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload