Reputation: 2391
I have a list of persons where one propery is a number as string, I would like to find all matches in that list that matches 2 numbers (a range).
public class car
{
public string Name { get; set; }
public string No { get; set; }
}
public void test()
{
var myList = new List<car>
{
new car {Name = "Volvo", No = "10"},
new car {Name = "Volvo", No = "20"},
new car {Name = "Volvo", No = "30"},
new car {Name = "Volvo", No = "40"},
new car {Name = "Volvo", No = "50"},
new car {Name = "Volvo", No = "60"}
};
var startNumber = 10;
var EndNumber = 30;
}
How can I filter out all the matches in the myList where No is within startNumber
and EndNumber
?
Upvotes: 0
Views: 2760
Reputation: 12196
This is a pretty straightforward solution:
myList
.Where(car => startNumber <= int.Parse(car.No) && int.Parse(car.No) <= EndNumber)
.ToList();
Note: If we can't assume No
will only contains Natural numbers, than using int.TryParse
will be a better alternative than int.Parse
.
Remarks:
No
as int
rather than string
.Number
or LicensePlate
it will be a little longer, but more concise.Car
, Animal
Local variables
should be lower cased. e.g: endNumber
var
when using Primitive variables like int
, double
etc`Upvotes: 4
Reputation: 223237
You have to parse the number to integer and then compare the range. You can also use Int.TryParse
to save yourself from the exception. To do the parsing once, make an anonymous type and then query like:
int temp;
var query = myList.Select(r => new
{
Car = r,
NumericNo = int.TryParse(r.No, out temp) ? temp : 0 //or -1 for invalid values
})
.Where(r => r.NumericNo >= start && r.NumericNo <= end)
.Select(r => r.Car);
You may also follow the General Naming Conventions
Upvotes: 1