我有一個類RuleDetail
:在c#中查詢的LINQ解決方案是什麼?
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或 - 獲取最大的
RuleDetail
對象(StartYear)時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中做到這一點?
感謝
我不知道你提供的解決方案是正確的?如果'ruleDetails [1] .StartYear == x + 1'和'ruleDetails [2] .StartYear == x'怎麼辦? –
RuleDetails []中的'RuleDetail'對象由StartYear排序。 – ChumboChappati