Skip to main content
 首页 » 编程设计

c#之按月将值放入数据表组

2024年02月13日14jpfss

我在 C# 中有这个数据表

 Date    Employee Job1   Job2     Job3 
1/1/2012    a    1      1          1  
1/1/2012    b    2      2          2 
1/1/2012    c    2      1          4 
1/1/2012    d    4      2          1 
1/2/2012    a    3      2          5 
1/2/2012    b    2      2          2 
1/2/2012    c    3      3          3 
1/2/2012    d    1      1          1 
1/3/2012    a    5      5          5 
1/3/2012    b    2      2          6 
1/3/2012    c    1      1          1 
1/3/2012    d    2      3          4 
2/1/2012    a    2      2.5        2 
2/1/2012    b    5      5          2 
2/1/2012    c    2      2          2 
2/2/2012    a    3      3          3 
2/2/2012    b    2      3          3 
3/1/2012    a    4      4          11 
3/5/2012    a    14     42.5       15 
3/6/2012    a    21     12.143     22 
3/8/2012    a    8.9    45         27 
3/8/2012    b    4.4    25         31 

我想按月遍历这些值,这样我就可以将值存储在数据表中,然后用它进行其他计算。在这个例子中,它将有三个数据表,第一个是一月的值,另一个是二月的,最后一个是三月的行。 Linq 怎么能做到这一点。请建议将按月对结果进行分组的 Linq 语法。

var monthEmpGroups = dt.AsEnumerable() 
                .Select(r => new 
                {                    
                    Year = DateTime.Parse(r.Field<string>("DATE")).Year, 
                    Month = DateTime.Parse(r.Field<string>("DATE")).Month.ToString() 
                }) 
                .GroupBy(x => x.Month); 
 
var dtf = CultureInfo.CurrentCulture.DateTimeFormat; 
foreach (var empGroup in monthEmpGroups) 
{ 
    int month = int.Parse(empGroup.Key); 
    string colName = dtf.GetMonthName(month); 
    // Here i want to get all the rows where month is colName (i.e.january, feb, march) 
} 

请建议是否有其他方法可以使用 LINQ 按月获取值。

请您参考如下方法:

您应该将获取每个组的项目移动到 monthEmpGroups 查询中:

var monthEmpGroups = (from r in dt.AsEnumerable() 
                      let month = DateTime.Parse(r.Field<string>("DATE")).Month 
                      group r by month into g 
                      select new { Month = g.Key, Items = g.ToList() }); 

有了它,您可以轻松获得想要的结果:

var dtf = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat; 
 
foreach (var empGroup in monthEmpGroups) 
{ 
    int month = empGroup.Month; 
    string colName = dtf.GetMonthName(month); 
    List<DataRow> items = empGroup.Items; 
}