Linq - 获取介于下限和上限之间的值

时间:2012-01-26 11:57:56

标签: c# linq

我有一份费用清单(linq到sql实体 - 如果相关) - 高费用,低费用(两者都是十进制值)。我传递的是property value - 比如90000,我想检查这个property最佳是否匹配一个(或 first <费用清单中的/ em>价值中的多少。

费用可能类似......

(费用较低 - 费用较高)

0 - 50000
50001 - 75000
75001 - 90000
90001 - 140000
190000 - 500000

在这些值中,90000最适合 75001 - 90000 band 之类的东西,所以我想拉出 FeeDetail 实体。我真的不知道使用什么操作符,感谢任何帮助,到目前为止我的代码是...

    [Test]
    public void GetFeeRange()
   {
        const int id = 44;
        var propValue = 90000;

        //get a specific fee entity, then get the range of fee details...
        var recommendedFees = RepoSession.All<Fee>()
            .Where(x =>
                   x.ClientSurveyTypeID == id)
            .GroupJoin(_readOnlySession.All<FeeDetail>(),
                       x => x.FeeID,
                       y => y.FeeID,
                       (x, y) => new
                                     {
                                         FeeDetail = y.DefaultIfEmpty()
                                     })
            .Select(x => x.FeeDetail)
            .SingleOrDefault();

        Assert.IsNotNull(recommendedFees);

       //order fees by lowest fee - *the bit I am stuck on*
        var bestMatch = recommendedFees.OrderBy(x => x.Lower)
            .TakeWhile(x => propValue >= x.Lower || propValue <= x.Upper)
            .FirstOrDefault();



    }

问题 - 如何进行范围检查?我需要什么样的linq运算符?不确定我是否应该执行一段时间,从该范围获得最佳费用?

注意:费用很容易就是......

(费用较低 - 费用较高)

0 - 50000
50001 - 75000
95001 - 140000
190000 - 500000

如果找到最佳匹配,请将 OR 拉出来获得最接近的匹配...也许我可以显示可用匹配列表,如果一个不匹配(足够接近)完全匹配

3 个答案:

答案 0 :(得分:5)

只需要一个简单的.Where即可:

var bestMatch = recommendedFees
              .Where(x => propValue >= x.Lower && propValue <= x.Upper)
              .OrderBy(x => x.Lower)                  
              .FirstOrDefault();

答案 1 :(得分:1)

怎么样......

recommendedFees.Where(x => x.upperFee >= theFee).OrderByDescending(x => x.upperFee).Take(1).FirstOrDefault();

答案 2 :(得分:1)

var myfee = 90000;
var myFoundFeeRange = (from feeRange in feeRanges 
          where feeRange.lowerfee <= myfee && myfee <= feeRange.upperfee 
          select feeRange ).First()

这将简单检查费用是否在边界内。并返回匹配的边界