如何将Case语句添加到我的LINQ查询

时间:2015-11-12 10:05:24

标签: c# mysql linq

我有一个使用Linq语句填充的JS表。我是LINQ的新手,我真的需要这个LINQ语句,以便我可以完成我的项目。 这是我的LINQ声明。 (那个语句错误,因为数据库值错误,linq会解决所有问题)

MSCDatabaseDataContext MSCDB = new MSCDatabaseDataContext();
var q = from row in MSCDB.Tbl_Campaigns
        join cs in MSCDB.tbl_StatusOfCampaigns on row.CampaignStatus equals cs.ID
        where ((row.CampaignStatus == 0) ||
           (row.CampaignStatus == 1) ||
           (row.CampaignStatus == 2) ||
           (row.CampaignStatus == 3))
        select new Campaign
        {
            CampaignID = row.CampaignId,
            CampaignName = row.CampaignName,
            Target = Convert.ToInt32(row.Target),
            Discount = Convert.ToInt32(row.Discount),
            CampaignSDate = Convert.ToDateTime(row.StartDate),
            CampaignEDate = Convert.ToDateTime(row.EndDate),
            CurrentStatus = replaceStatus((row.CampaignStatus.ToString())),
            Uptake = Convert.ToInt32(row.Uptake),
        };

我基本上想删除那里的caluse和内连接,我可以有一个Case语句来显示基于日期的值。

CASE 
    WHEN EndDate >= GETDATE() and StartDate <= GETDATE() THEN 'Active' 
    WHEN StartDate >= GETDATE() THEN 'Pending'
    ELSE 'Closed' 
    END as 'CurrentStatus',

非常感谢帮助。 (您可以删除caluse和inner join所在的位置,因为它不需要。)

1 个答案:

答案 0 :(得分:2)

使用conditional operator,您可以在一行中解决此问题

CurrentStatus = row.EndDate >= DateTime.Now && row.StartDate <= DateTime.Now ? "Active": row.StartDate >=  DateTime.Now ? "Pending": "Closed";