Linq Select Substring列的值为1的值

时间:2014-11-18 23:18:44

标签: c# sql linq

我这里有时间表,然后我想用这个结果选择这个表

Code    Days
CS1     MT           AS Monday and Tuesday
CS2     WTH          AS Wednesday and Tuesday
ENG1    MWF          AS Monday, Wednesday and Friday
ENG1    SAT1         AS Saturday 1

我在linq上试过这个,结果是这个

enter image description here

使用Linq

from a in Schedules
select new 
{
    a.ScheduleID,
    a.ScCode,
    Days = a.Mon == 1 ? "M" : a.Tue == 1 ? "T" : a.Wed == 1 ? "W" : a.Thu == 1 ? "TH" : a.Fri == 1 ? "F" : a.Sat == 1 ? "SAT" : a.Sun == 1 ? "SUN" : "NO SCHEDULE"
}

让我失望。

有人对此有所了解吗?我在这里准备了材料http://sqlfiddle.com/#!3/5ef5d/1

感谢。

1 个答案:

答案 0 :(得分:1)

虽然我同意@shoe的意见,因为设计很可能是问题的最大部分,但我也相信能够满足人们的需求并帮助他们。话虽如此,这是你的答案:

from a in Schedules
select new
{
    a.ScheduleID,
    a.ScCode,
    Days = GetDays(a)
};

您正在寻找的内容包括以下方法:

private string GetDays(Schedule schedule)
{
    var stringBuilder = new StringBuilder();

    if (schedule.Mon == 1)
    {
        stringBuilder.Append("M");
    }

    if (schedule.Tue == 1)
    {
        stringBuilder.Append("T");
    }

    if (schedule.Wed == 1)
    {
        stringBuilder.Append("W");
    }

    if (schedule.Thu == 1)
    {
        stringBuilder.Append("TH");
    }

    if (schedule.Fri == 1)
    {
        stringBuilder.Append("F");
    }

    if (schedule.Sat == 1)
    {
        stringBuilder.Append("SAT");
    }

    if (schedule.Sun == 1)
    {
        stringBuilder.Append("SUN");
    }

    if (schedule.Mon1 == 1)
    {
        stringBuilder.Append("M1");
    }

    if (schedule.Tue1 == 1)
    {
        stringBuilder.Append("T1");
    }

    if (schedule.Wed1 == 1)
    {
        stringBuilder.Append("W1");
    }

    if (schedule.Thu1 == 1)
    {
        stringBuilder.Append("TH1");
    }

    if (schedule.Fri1 == 1)
    {
        stringBuilder.Append("F1");
    }

    if (schedule.Sat1 == 1)
    {
        stringBuilder.Append("SAT1");
    }

    if (schedule.Sun1 == 1)
    {
        stringBuilder.Append("SUN1");
    }

    if (stringBuilder.Length == 0)
    {
        stringBuilder.Append("NO SCHEDULE");
    }

    return stringBuilder.ToString();
}