Search code examples
c#listsortinglambda

How to change one field in a list<class> using lambda?


I have a list of objects, instances of a class. The class has several fields. One of the fields is a number. I want to sort the list by this numeric field, but in order to sort this field must be converted (abs from difference of field value and constant)

var t = myList.Min(a => Math.Abs(a.q - 10));

I expect the list to be sorted by a numeric field, which has been converted as taking the absolute value of the difference between the field value and the constant. For example, I have

myList[0].a = 3;
myList[1].a = 7;

So, during sorting, this should happen:

myList[0].a = abs(3-10);//7
myList[1].a = abs(7-10);//3
var t = myList[1];//

Solution

  • You can use LINQ OrderBy, here is an example:

    List<int> myList = new List<int> { 3, 7 };
    int myConst = 10;
    List<int> sortedList = myList.OrderBy(x => Math.Abs(x - myConst)).ToList();