将缺少的枚举添加到列表C#

时间:2017-03-03 22:24:13

标签: c# asp.net asp.net-mvc linq enumeration

我写了一个以下代码,基本上按天划分我的销售额,然后我在图表上向用户显示如下:

   var DailyGraph = userStores.ToList().GroupBy(x => x.TransactionDate.Value.DayOfWeek).Select(pr => new { Day = pr.Key.ToString(), Sales = pr.Sum(x => x.QuantitySoldTransaction) });
   var dayIndex = new List<string> { "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY" };
   ViewBag.DailyGraph = DailyGraph.OrderBy(e => dayIndex.IndexOf(e.Day.ToUpper())).ToList();

好的,这里发生了什么,在第一行我将所有可用的销售额按星期几参数分组,即Enumeration ...然后我创建一个包含精确日期名称的字符串列表,如Enumeration,我将它们进行比较我可以按天的顺序(星期一到星期日)订购它们......

我现在的问题是,如果用户在特定日期没有销售......我们说周一和周四他没有销售......我怎么能现在添加这些我的名单上缺少几天?由于我正在使用枚举,我对如何做到有点困惑......

所以当前的输出是:

Tuesday    5 sales
Wednesday  9 sales
Friday     4 sales
Saturday   13 sales
Sunday     5 sales

所需的输出是:

Monday     0 sales // Add missing day enumeration and assign 0 value
Tuesday    5 sales
Wednesday  9 sales
Thursday   0 sales // Add missing day enumeration and assign 0 value
Friday     4 sales
Saturday   13 sales
Sunday     5 sales

有人能帮助我吗?

丹,这样的事吗?

for (int i = 0; i < DailyGraph.Count(); i++)
                    {
                        if (!dayIndex.Contains(DailyGraph[i].Day.ToUpper()))
                        {
                            DailyGraph.Add(new HourlyGraph { Day = dayIndex.ElementAt(i), Sales = 0 });
                        }
                    }

4 个答案:

答案 0 :(得分:2)

你可以在最后添加缺失的日子,例如:

DailyGraph.AddRange(
   dayIndex.Except(DailyGraph.Select(t => t.Day)).Select(r => new { Day = r, Sales = 0 }));

答案 1 :(得分:2)

首先,我不会使用字符串作为您的密钥,因为如果有人不使用英语,这可能不起作用。

你可以这样做:

var dayIndex = new List<DayOfWeek> { DayOfWeek.Monday, DayOfWeek.Tuesday, /* etc */   };
var DailySales = dayIndex.Select(d => new { Day = d, Sales =
     userStores.Where(x => x.TransactionDate.Value.DayOfWeek == d)
     .Sum(u => u.QuantitySoldTransaction) }).ToList();

答案 2 :(得分:2)

获取一周中所有可用日期,并使用您计算的每日图表执行左外连接:

Name      Approved
Google    true
Facebook  true
Apple     false
Trulia    true
Google    false
Trulia    true

答案 3 :(得分:1)

您可以使用.ToLookup()子句,并注意假设您的视图模型是

,那么您的日期名称列表并不是必需的
public class HourlyGraph
{
    public DayOfWeek Day { get; set; }
    public int Sales { get; set; }
}

查询

var lookup = userStores.ToLookup(x => (int)x.TransactionDate.DayOfWeek);
ViewBag.DailyGraph = from day in Enumerable.Range(0, 7)
                     select new HourlyGraph
                     {
                         Day = (DayOfWeek)day,
                         Sales = lookup[day].Sum(x => x.QuantitySoldTransaction)
                     };

请注意,记录将按周日至周六的顺序打印