我有一个课程RuleDetail

public class RuleDetail
{
   public int RuleDetailId;
   public int StartYear;
}


我有一个RuleDetail类型的对象列表:


  RuleDetailId = 1,StartYear = 0
  RuleDetailId = 2,StartYear = 2
  RuleDetailId = 3,StartYear = 4
  RuleDetailId = 4,StartYear = 10
  RuleDetailId = 5,StartYear = 13
  RuleDetailId = 6,StartYear = 18


我将得到一个数字,表示x(x始终> = 0);为此,我需要在上述列表中找到与这些条件匹配的RuleDetail对象:


获取RuleDetail对象,其中x等于StartYear或
当StartYear RuleDetail对象


假设我有这些变量

RuleDetail[] ruleDetails = null;
int x = -1;
// ruleDetails populated
// x populated


这是我想出的代码:

bool found = false;
RuleDetail ruleDetail = null;
RuleDetail oldRuleDetail = null;

for (int i=0; i<ruleDetails.Length; i++)
{
   if (ruleDetails[i].StartYear == x)
   {
      found = true;
      ruleDetail = ruleDetails[i];
      break;
   }
   else if (ruleDetails[i].StartYear > x)
   {
      found = true;
      ruleDetail = oldRuleDetail;
      break;
   }

   oldRuleDetail = ruleDetails[i];
}
if (!found)
{
    ruleDetail = oldRuleDetail;
}
return ruleDetail;


该代码工作正常。但是如何在LINQ中做到这一点?

谢谢

最佳答案

var output = ruleDetails.OrderBy(rule => rule.StartYear).Where(rule => rule.StartYear <= x).Last()


如果列表已经按StartYear顺序排列,则....

var output = ruleDetails.Where(rule => rule.StartYear <= x).Last()

关于c# - 在C#中此查询的LINQ解决方案是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33487041/

10-11 15:59