Linq:查找范围内的值

时间:2021-06-23 15:06:59

标签: linq 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.
               };

1 个答案:

答案 0 :(得分:1)

由于您使用的是 LINQ to Objects,并且假设 boundariesList<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 方法。

相关问题