根据星期几执行查询

时间:2017-06-26 14:22:12

标签: c#

我试图运行一段代码,这些代码取决于星期几将从sql列返回一条信息(由星期几指定)我目前有一段详细的代码就像这样。

 public void ErrorTest()
{
    using (ScraperSetupEntities context = new ScraperSetupEntities())
    {
        int collectionavg;
        string today = DateTime.Now.DayOfWeek.ToString();
        if (today == "Sunday")
        {
            collectionavg = context.FourWeekCollectionReports.First().FourWeekSundayCollected;
        }
        if (today == "Monday")
        {
            collectionavg = context.FourWeekCollectionReports.First().FourWeekMondayCollected;
        }   
        // etc etc for every day of the week
    }
}

我知道在t-sql中我可以有一个文字字符串,并将星期几附加到" FourWeek" +今天+"收集"然后将字符串作为查询运行,但我无法弄清楚如何在c#中做类似的事情。任何帮助,将不胜感激。感谢

2 个答案:

答案 0 :(得分:1)

使其成为一种功能......

您可以使用Linq的Where()函数从WeekCollection中选择正确的日期。

然后您可以再次使用Linq的Select()函数返回平均收集计数。

public int GetCollectionAvgFromDay(ScraperSetupEntities context, string DayOfWeek)
{
    return context.FourWeekCollectionReports.First().Where(x => x.Day == DayOfWeek).Select(x => x.CollectionAvg);
}

WeekCollectionReport应包含的内容:

public class WeekCollectionReport
{
    public string Day {get; set;}
    public int CollectionAvg {get; set;}
}

要打电话,只需:

public void ErrorTest()
{
    using (ScraperSetupEntities context = new ScraperSetupEntities())
    {
        int collectionavg;
        string today = DateTime.Now.DayOfWeek.ToString();
        collectionavg = GetCollectionAvgFromDay(context, today);
    }
}

答案 1 :(得分:0)

除非你想改变设计,否则你无法真正做到这一点。如果您不想让代码更小/更清洁

,您可以将代码模式化为您的模型

e.g。

public class Report
{
    public int SundayAvg { get; set; }
    public int MondayAvg { get; set; }
    public int TuesdayAvg { get; set; }

    //new property that just returns Todays average. 
    public int TodayAverage => GetTodayAverage();


    public int GetTodayAverage()
    {
        switch (DateTime.Today.DayOfWeek)
        {
            case DayOfWeek.Sunday:
                return SundayAvg;
            case DayOfWeek.Monday:
                return MondayAvg;
            case DayOfWeek.Tuesday:
                return TuesdayAvg;
             ...
            default:
                //How the hell did that happen;
                return 0;

        }
    }
}

...然后你可以问TodayAverage

List<Report> report = new List<Report>();
report.Add(new Report() { SundayAvg = 1, MondayAvg = 2, TuesdayAvg = 3 });

var a = report.First().TodayAverage;