Reputation: 18630
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.
Upvotes: 1
Views: 113
Reputation: 48568
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());
Upvotes: 0
Reputation: 460098
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.
Upvotes: 3
Reputation: 50114
You can use MoreLinq's MinBy method to find the person with the minimum value, without having to sort all your people, which will be inefficient if you have more than a few of them.
Person lowPerson = people.MinBy(p => int.Parse(p.ReferenceString));
Upvotes: 0
Reputation: 5600
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.
Upvotes: 0