Reputation: 157
am in a middle of project , and am kind of stuck on the problem,
i need to sort a list in C#
the list structure is
public List < double[] > DataList = new List < double[] >();
now i want to sort this list on the bases of the last index of double array in the list
like
2|3|5|6|8
2|3|5|6|9
2|3|5|6|5
2|3|5|6|12
the output should be some thing like this
2|3|5|6|12
2|3|5|6|9
2|3|5|6|8
2|3|5|6|5
Upvotes: 0
Views: 151
Reputation: 8656
This is some old school sorting without using the LINQ.
List<double[]> DataList = new List<double[]>();
private void button1_Click(object sender, EventArgs e)
{
DataList.Add(new double[] { 2, 3, 5, 6, 8 });
DataList.Add(new double[] { 2, 3, 5, 6, 9 });
DataList.Add(new double[] { 2, 3, 5, 6, 5 });
DataList.Add(new double[] { 2, 3, 5, 6, 12 });
DataList.Sort(new DoubleArrayComparer());
DataList.Reverse();
}
class DoubleArrayComparer : IComparer<double[]>
{
public int Compare(double[] x, double[] y)
{
if(x.Length>0 && y.Length>0)
{
if(x[x.Length-1] > y[y.Length-1])
return 1;
else if(x[x.Length-1] < y[y.Length-1])
return -1;
else
return 0;
}
else if(x.Length == 0 && y.Length!=0)
return -1;
else if(y.Length == 0 && x.Length!=0)
return 1;
else
return 0;
}
}
Upvotes: -1
Reputation:
Also using Linq:
var tList = new List<double[]>();
tList.Add(new double[] {2,3,4,5,8});
tList.Add(new double[] {2,3,4,5,9});
tList.Add(new double[] {2,3,4,5,5});
tList.Add(new double[] {2,3,4,5,12});
var t = from element in tList
orderby element.Last() descending
select element;
var tResults = t.ToList();
Upvotes: 0
Reputation: 8488
Use LINQ:
// reproduce data
List<double[]> DataList = new List<double[]>();
DataList.Add(new double[] { 2, 3, 5, 6, 8 });
DataList.Add(new double[] { 2, 3, 5, 6, 9 });
DataList.Add(new double[] { 2, 3, 5, 6, 5 });
DataList.Add(new double[] { 2, 3, 5, 6, 12 });
var ordered = DataList.OrderByDescending(l => l.Last());
l
would correspond to each element in DataList
. With l.Last()
you use the last element as sorting criterion.
Upvotes: 3