日期数组,检查日期是否存在

时间:2015-10-15 08:56:44

标签: c# linq

我有一个对象成员,

Member
 PropertyA
 PropertyZ
 Membership[] Memberships

和Membership对象是

Membership
 PropertyA
 PropertyZ
 string Status
 DateTime? StartDate 
 DateTime? EndDate 

如果我现在有,

var members = GetAllMembers(DateTime.Now);

我想了解会员今天是否有任何有效会员资格

   // iterating through each member here
   if(member.Memberships.Any())
   {
       // check if user has any membership duration that falls into 
       // today's date and membership status is also "active"
   }

问题是,

我不确定如何检查今天的会员资格持续时间和成员资格状态是否也“有效”

3 个答案:

答案 0 :(得分:2)

检查targetdt(DateTime.Now)是否在StartDate和amp;之间。结束日期:

if (member.Memberships.Any(x=>targetDt.Ticks > x.StartDate.Ticks && targetDt.Ticks < x.EndDate.Ticks && x.Status=="Active"))
{
    // Has membership on targetDt.
}  

答案 1 :(得分:2)

我认为开始日期或结束日期的空值意味着“打开”#39;间隔

dummy

答案 2 :(得分:2)

因此,我会将您的主要课程与您现有的课程略有不同。这需要比较状态的字符串,但由于我不确切知道如何设置active属性,但我认为成员资格是活动的,开始和(可选)结束日期必须小于和大于今天的日期。

class Member
{
    private readonly IList<Membership> memberships;

    public Member()
    {
        memberships = new List<Membership>();
    }

    public ReadOnlyCollection<Membership> Memberships 
    { 
        get
        {
            return new ReadOnlyCollection<Membership>(memberships);
        }
    }
}

class Membership
{
    private readonly DateTime endDate;

    private readonly DateTime startDate;

    public Membership(DateTime startDate)
    {
        this.startDate = startDate;
    }

    DateTime StartDate 
    {
        get
        {
            return this.startDate;
        }
    }

    DateTime? EndDate 
    { 
        get
        {
            return endDate;
        }
    }

    public Status Status
    {
        get
        {
            return CalculateMemebershipStatus();
        }
    }

    private Status CalculateMemebershipStatus()
    {
        var todaysDate = DateTime.Today;

        if (StartDate > todaysDate)
        {
            return Status.Deactivated;
        }

        if (!EndDate.HasValue)
        {
            return Status.Active;
        }

        if (todaysDate < EndDate.Value)
        {
            return Status.Active;
        }

        return Status.Deactivated;
    }
}

enum Status
{
    Active,
    Deactivated
}

如果您需要查找今天拥有active会员资格的所有会员,您可以这样做:

var memberCollection = new List<Member>();
...
var activeMembers = memberCollection.Where(x => x.Memberships.Any(y=> y.Status == Status.Active));

因此,这将通过您的成员集合并选择今天具有活动状态的成员集合。虽然如前所述,这取决于您如何构建active属性,但这更多地包含在基于日期的membership的活动性测试中,在成员资格对象内完成。因此,此数据的消费者不需要知道如何说membershipactive他们只需要知道某些人将处于活动状态而其他人将被停用。