我试图显示在特定日期售出的商品数量。销售细节数据看起来像这个
DetailID | Items | Quantity | salesDate | 0 | 0 | 面条 | 1 | 17/02/2021 |
---|---|---|---|---|
0 | 1 | 汉堡 | 1 | 17/02/2021 |
0 | 2 | 沙拉 | 1 | 17/02/2021 |
3 | 薯条 | 1 | 18/02/2021 | |
4 | 面条 | 1 | 18/02/2021 | |
5 | 面条 | 1 | 18/02/2021 | |
3 | 6 | 薯条 | 1 | 19/02/2021 |
7 | 面条 | 1 | 19/02/2021 | |
8 | 面条 | 1 | 20/02/2021 |
参见:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Globalization;
namespace ConsoleApplication181
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("SalesID", typeof(int));
dt.Columns.Add("DetailID", typeof(int));
dt.Columns.Add("Items", typeof(string));
dt.Columns.Add("Quantity", typeof(int));
dt.Columns.Add("salesDate", typeof(DateTime));
dt.Rows.Add(new object[] {0, 0, "noodles",1, DateTime.ParseExact("17/02/2021", "dd/mm/yyyy", CultureInfo.InvariantCulture)});
dt.Rows.Add(new object[] {0, 1, "burger",1, DateTime.ParseExact("17/02/2021", "dd/mm/yyyy", CultureInfo.InvariantCulture)});
dt.Rows.Add(new object[] {0, 2, "salad",1, DateTime.ParseExact("17/02/2021", "dd/mm/yyyy", CultureInfo.InvariantCulture)});
dt.Rows.Add(new object[] {1, 3, "fries",1, DateTime.ParseExact("18/02/2021", "dd/mm/yyyy", CultureInfo.InvariantCulture)});
dt.Rows.Add(new object[] {2, 4, "noodles",1, DateTime.ParseExact("18/02/2021", "dd/mm/yyyy", CultureInfo.InvariantCulture)});
dt.Rows.Add(new object[] {2, 5, "noodles",1, DateTime.ParseExact("18/02/2021", "dd/mm/yyyy", CultureInfo.InvariantCulture)});
dt.Rows.Add(new object[] {3, 6, "fries",1, DateTime.ParseExact("19/02/2021", "dd/mm/yyyy", CultureInfo.InvariantCulture)});
dt.Rows.Add(new object[] {4, 7, "noodles",1, DateTime.ParseExact("19/02/2021", "dd/mm/yyyy", CultureInfo.InvariantCulture)});
dt.Rows.Add(new object[] {5, 8, "noodles",1, DateTime.ParseExact("20/02/2021", "dd/mm/yyyy", CultureInfo.InvariantCulture)});
DataTable dt2 = new DataTable();
dt2.Columns.Add("Items", typeof(string));
dt2.Columns.Add("ItemsSold", typeof(int));
var groups = dt.AsEnumerable().GroupBy(x => x.Field<string>("Items")).ToList();
foreach (var group in groups)
{
dt2.Rows.Add(new object[] {group.Key, group.Count()});
}
}
}
}