添加一个“;当“然后”;条款

本文关键字:条款 然后 一个 添加 | 更新日期: 2023-09-27 18:24:00

我有一个LINQ查询来填充我的管理面板表。在其中,我有一个case语句,用于根据活动的日期填充字段。(也就是说,如果开始日期小于DateTime.Now,那么它将显示为活动,如下所示。)我想做的是在该case语句中添加一个where条件,将EndDate更新为DateTime.Now,使其关闭。要检查的条件是我的Uptake是否已达到我的Target,这意味着如果已达到活动所需的目标,则活动将关闭。有人能帮帮我吗?

MSCDatabaseDataContext MSCDB = new MSCDatabaseDataContext();
var q =
    from row in MSCDB.Tbl_Campaigns
    where row.CampaignStatus != 4
    select new Campaign
    {
        CampaignID = row.CampaignId,
        CampaignName = row.CampaignName,
        Target = Convert.ToInt32(row.Target),
        Discount = Convert.ToInt32(row.Discount),
        CampaignStartDatesS =
            Convert.ToDateTime(row.StartDate).Date + " - " +
            Convert.ToDateTime(row.EndDate).Date,
        //CampaignSDate = Convert.ToDateTime(row.StartDate),
        //CampaignEDate = Convert.ToDateTime(row.EndDate),
        CurrentStatus =
            (row.EndDate >= DateTime.Now && row.StartDate <= DateTime.Now) ? "Active" :
            row.StartDate >= DateTime.Now ? "Pending" :
            row.CampaignStatus == 4 ? "Archived" : "Closed",
        Uptake = Convert.ToInt32(row.Uptake),
    };

添加一个“;当“然后”;条款

您可以使用let预先计算在select:中使用的值

var q = from row in MSCDB.Tbl_Campaigns
        let target = Convert.ToInt32(row.Target)
        let uptake = Convert.ToInt32(row.Uptake)
        where row.CampaignStatus != 4
        select new Campaign
        {
            CampaignID = row.CampaignId,
            CampaignName = row.CampaignName,
            Target = target,
            Discount = Convert.ToInt32(row.Discount),
            CampaignStartDatesS = Convert.ToDateTime(row.StartDate).Date + " - " + Convert.ToDateTime(row.EndDate).Date,
            CurrentStatus = uptake >= target ? "Closed" : row.EndDate >= DateTime.Now && row.StartDate <= DateTime.Now ? "Active": row.StartDate >=  DateTime.Now ? "Pending": row.CampaignStatus == 4 ? "Archived": "Closed",
            Uptake = uptake
        };

为什么不这样做:

MSCDatabaseDataContext MSCDB = new MSCDatabaseDataContext();
var q = from row in MSCDB.Tbl_Campaigns
where row.CampaignStatus != 4
select new Campaign
{   
    CampaignID = row.CampaignId,
    CampaignName = row.CampaignName,
    Target = Convert.ToInt32(row.Target),
    Discount = Convert.ToInt32(row.Discount),
    CampaignStartDatesS = Convert.ToDateTime(row.StartDate).Date + " - " + Convert.ToDateTime(row.EndDate).Date,
    //CampaignSDate = Convert.ToDateTime(row.StartDate),
    CampaignEDate = Convert.ToInt32(row.Uptake) == Convert.ToInt32(row.Target) ? DateTime.Now : null,
    CurrentStatus = row.EndDate >= DateTime.Now && row.StartDate <= DateTime.Now ? "Active": row.StartDate >=  DateTime.Now ? "Pending": row.CampaignStatus == 4 ? "Archived": "Closed",
    Uptake = Convert.ToInt32(row.Uptake),
};