I have a C# custom object list that I need to sort by two different variables one is a boolean and the other is a string. I can sort by either of the criteria, but
I was able to do something fast/dirty by doing this.. since both columns are text, just add them together to sort in one quick pass.
this.Project.Tasks.Sort((x, y) => String.Compare((x.Assignee + x.Task), (y.Assignee + y.Task)));
Comparison Chain in C#
Here's my comparison chain solution. It will take care of aggregating all comparer classes you are interested in sorting by. the builder pattern makes it easy to provide columns to sort by and get a sorted list in return.
var sortResult = result.OrderBy(a => a.CheckedIn).ThenBy(a => a.LastName).ToList();
I have a class that creates CSV files using List<List<string>>
in a _Records
variable. I needed way to sort it after the fact, and LINQ was no good.
This is what I created as a multi-sort by passing in the indexes of the columns I wanted to sort.
public void OrderBy(params int[] columnIndexes)
{
_Records.Sort((x, y) =>
{
foreach (int i in columnIndexes)
{
int result = string.Compare(x[i], y[i]);
if (result != 0)
return result;
}
return 0;
});
}
Usage would then be...
csv.OrderBy(1, 3, 5);
use linq.
if you have list L of objects of class
public class temp
{
public bool x;
public string y;
}
then use:
L.orderby(a=>a.x).thenby(a=>a.y);
you can chain it as far as you like.
result.Sort((x,y) => x.CheckedIn==y.CheckedIn ?
string.Compare(x.LastName, y.LastName) :
(x.CheckedIn ? -1 : 1) );