Linq:查找范围内的值

Linq: Finding values within a range

我想根据提供的范围将 1 个 Linq 查询与另一个匹配。

例如,查找姓氏在'sa'和'sn'之间的所有学生。然后,我希望找到姓氏为 Smith 和 Sammy 的学生,但不包括 Swann 和 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.
               };

由于您正在使用 LINQ to Objects,并且假设 boundaries 是一个 List<T> 条件,其中任何一个都需要匹配,您可以测试 Students 中的每个学生对象针对每个边界:

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

注意:不幸的是,C# 没有关系字符串运算符,任何地方的扩展都没有完成,因此您必须使用 CompareTo 方法。