简体   繁体   中英

How to get the property from a list of object that is a string with the lowest numeric value

Say I have a list of people:

Var people = new List<Person>();

Where

Public class Person {
Public string ReferenceString { get; set; }
}

The reference string is a string of digits so I might have in my list;

Var person1 = new Person { ReferenceString = "12" };
Var person2  = new Person { ReferenceString = "11" };
Var person3 = new Person { ReferenceString = "14" };

What I want to do is somehow get back the reference string with the lowest numeric value which in this case is "11". So I'm guessing it will need to be converted to an int somewhere on the line and was working along the lines of something like:

people.Where(x => Int32.Parse(x.ReferenceString));

Not sure how to do the comparison though.

You need to convert it to an int, order by that value and take the first(lowest):

Person lowPerson = people.OrderBy(p => int.Parse(p.ReferenceString)).First();

If you only want the lowest value:

int lowest = people.Min(p => int.Parse(p.ReferenceString));

But you should consider to store it as int in the first place.

Your code will give error because ReferenceString is string and you are assigning integer value to it.

Since you said you cannot change datatype you can do

Var person1 = new Person { ReferenceString = "12" };
Var person2  = new Person { ReferenceString = '11" };
Var person3 = new Person { ReferenceString = "14" };

In that case use

var min = people.Min(x => Convert.ToInt32(x.ReferenceString));

In case you want to find out which pesons have min ReferenceString, you can do.

var result = people.Where(x => x.ReferenceString == min.ToString());

I would make ReferenceString as ReferenceInteger if it is storing numbers. Then, you can use Min method and get the records. Like this:

var person1 = new Person { ReferenceString = 12 };
            var person2 = new Person { ReferenceString = 11 };
            var person3 = new Person { ReferenceString = 14 };

            var people = new List<Person>();
            people.Add(person1);
            people.Add(person3);
            people.Add(person2);

            var returnValues = people.Where(x => x.ReferenceString == people.Min(y => y.ReferenceString));

Here ReferenceString is of type integer. Consider renaming the property accordingly.

您可以使用MoreLinq的MinBy方法来查找具有最小值的人,而无需对所有人进行排序,如果您有多个人,则效率低下。

Person lowPerson = people.MinBy(p => int.Parse(p.ReferenceString));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM