How to query data by month in LINQ?

In LINQ, you can use the GroupBy method to group data by month and use the DateTime.Month property to get the month of the date.

Here is an example code that demonstrates how to query data by month.

// 假设有一个包含日期和数据的列表
List<DataItem> data = new List<DataItem>()
{
    new DataItem { Date = new DateTime(2022, 1, 15), Value = 10 },
    new DataItem { Date = new DateTime(2022, 2, 25), Value = 20 },
    new DataItem { Date = new DateTime(2022, 1, 5), Value = 30 },
    new DataItem { Date = new DateTime(2022, 3, 10), Value = 40 },
    new DataItem { Date = new DateTime(2022, 2, 10), Value = 50 }
};

// 按月份分组并查询
var result = data.GroupBy(item => item.Date.Month)
                 .Select(group => new {
                     Month = group.Key,
                     Sum = group.Sum(item => item.Value)
                 });

// 输出结果
foreach (var item in result)
{
    Console.WriteLine($"Month: {item.Month}, Sum: {item.Sum}");
}

In this example, we start by grouping the data by month using the GroupBy method. Then, we use the Select method to process each group, creating a new anonymous type object that includes the month and the total sum of data for that month. Finally, we output the results using a foreach loop.

Please note that the DataItem class in the example is a custom data item class used to store dates and data values. You will need to make adjustments according to your own data structure.

bannerAds