MTplus
MTplus

Reputation: 2391

How to find all matches in linq list between 2 numbers

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

Answers (2)

Orel Eraki
Orel Eraki

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:

  1. I highly recommend you to save No as int rather than string.
  2. Also don't be cheap on Property names, If you will use Number or LicensePlate it will be a little longer, but more concise.
  3. You should follow .NET naming conventions by using class names with Capital letters. e.g: Car, Animal
  4. First letter in Local variables should be lower cased. e.g: endNumber
  5. It's a good practice to avoid var when using Primitive variables like int, double etc`

Upvotes: 4

Habib
Habib

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

Related Questions