Cameron Castillo
Cameron Castillo

Reputation: 2862

Linq: Finding values within a range

I would like to match 1 Linq query with another one, based on a range provided.

For example, find all students with surnames between 'sa' and 'sn'. I'm looking to then find students with surnames Smith and Sammy, but not Swann and Anderson.

var allStudents = from s in Students select s;
var boundary = from b in boundaries select new { LowEnd = b.start, HighEnd = b.end }; //LowEnd = "sa" and HighEnd = "sn"

var matches = from s in allStudents
              select new
              {
                  s.Surname > boundary.LowEnd && s.Surname <= boundary.HighEnd
                  //This will obviously give a compile error, but not sure how to do it.
               };

Upvotes: 0

Views: 549

Answers (1)

NetMage
NetMage

Reputation: 26936

Since you are using LINQ to Objects, and assuming boundaries is a List<T> of conditions any one of which needs to be matched, you can test each student object from Students against each boundary:

var matches = from s in Students
              where boundaries.Any(b => b.start.CompareTo(s.Surname) <= 0 && s.Surname.CompareTo(b.end) <= 0)
              select s;

NOTE: Unfortunately C# doesn't have relational string operators and extensions anywhere isn't done, so you must use the CompareTo method.

Upvotes: 1

Related Questions