Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading