首页 > 解决方案 > 强制计算 A Duration To Year

问题描述

我有一个要求,我必须强制将持续时间显示为两年完成。例如,从 2016 年到 2018 年在应用程序中在线活跃的任何客户都应被视为在应用程序中完成两年。这看起来很简单,并使用以下Linq方法使其工作:

var result = (from c in db.Users
              where c.UserId == id && (c.Start.Year >= 2016 && c.End.Year <= 2018)
              select c).ToList ();

 int years = 0;
 if (result.Count () > 0)
 {
     years = 2;
 }
 else
 {
    //Logic goes here
 }

所以可以看出我是在强迫它计算两年的持续时间。根据这一点,我将授予用户系统中 20% 的忠诚度。虽然我构建逻辑有点复杂。同样,在该范围内,用户可能在 2016 年到 2017 年期间处于活跃状态。因此这些用户将没有资格获得忠诚度。

对于不符合条件的用户,我如何才能使上述两个条件同时工作两年?任何想法,将不胜感激。

标签: c#asp.net.netlinq

解决方案


I think this is what you are after. It gets the user and determines the timespan between start year and end year assigns that value to years and then checks if it's less than 2. If so do your logic. I'm making the assumption that UserId is unique and there will always be at least one entry.

Here is a working Fiddle: https://dotnetfiddle.net/bVDpkF

var result = (
    from c in db.Users
    where c.UserId == id
    select c).Single();



int years =  result.End.Year - result.Start.Year;

if (years <= 2)
{
//Logic goes here
}

推荐阅读