我有一个班级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
对象或RuleDetail
对象,当StartYear< X 假设我有这些变量
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中做到这一点?
由于
答案 0 :(得分:3)
var output = ruleDetails.OrderBy(rule => rule.StartYear).Where(rule => rule.StartYear <= x).Last()
如果列表已经在StartYear中,那么......
var output = ruleDetails.Where(rule => rule.StartYear <= x).Last()
答案 1 :(得分:2)
您可以使用
ruleDetails.FirstOrDefault(rd => rd.StartYear == x)
?? ruleDetails.Where(rd => rd.StartYear < x).OrderByDescending(rd => rd.StartYear).First();
这是对您的两个要求的明确分离,但实际上使用
更简洁ruleDetails.Where(rd => rd.StartYear <= x).OrderByDescending(rd => rd.StartYear).First()
答案 2 :(得分:1)
var res1 = (from a in ruleDetails where a.StartYear == x select a).First();
var res2 = (from a in ruleDetails orderby a.StartYear where a.StartYear < x select a).Last();
答案 3 :(得分:1)
这是一个真正简单的LINQ代码片段,可以完成您在此处尝试的操作。我写这篇文章时假设您的列表是按照当前代码的建议排序的。
我们首先将列表过滤到目标年份或小于目标年份的条目,然后获取剩余的最高元素。
var filteredList = ruledetails.Where(r => r.StartYear <= targetYear);
return filteredList.Last;
答案 4 :(得分:1)
它有点粗,但可能是这样的:
var result = ruleDetails
.OrderBy(r => r.StartYear)
.FirstOrDefault(r => r.StartYear == x || r.StartYear == ruleDetails.Select(y => y.StartYear).Max());
答案 5 :(得分:1)
(A)如果列表最初按var result = ruleDetails.LastOrDefault(r => r.StartYear <= startYear);
排序,则
var result = ruleDetails.Where(r => r.StartYear <= startYear)
.Aggregate((RuleDetail)null, (a, b) => a == null || a.StartYear < b.StartYear ? b : a);
(B)如果列表没有排序,那么
call __RTC_UninitUse