Linq查询按状态计数

时间:2016-03-04 11:32:14

标签: c# linq

我想在数据表中明智地计算项目状态。

我的数据表看起来像

Date , Tkt Status
1/2/13    open
1/2/13    open
2/2/13    open
2/2/13    closed
2/2/13    closed
3/3/13    in-progress
4/3/13    closed 

我希望另一个数据表格式为

以下数据
Date, Open, Closed, in-progress
1/2/13   2        0            0
2/2/13   1        2            0
3/3/13   0        0            1
4/3/13   0        1            0

我希望使用Linq完成它。

到目前为止我的尝试

dataQuery.Query =“是”;

                    dataQuery.ViewFields = "<FieldRef Name='Created' /><FieldRef Name='tckPrty' /><FieldRef Name='tckStat' />";
                    dataQuery.ViewFieldsOnly = true;
                    tktData = tktList.GetItems(dataQuery).GetDataTable();

                    var newData = from row in tktData.AsEnumerable()
                                  where groupDate(row.Field<string>("tckStat"))
                                          group row by row.Field<string>("Created") into Status
                                          orderby Status.Key
                                          select new
                                          {
                                              key = Status.Key,
                                              values = Status,
                                              count = Status.Count()
                                          };

                    foreach (var item in newData)
                    {
                        foreach (string s in tktStatus)
                        {
                            chartData.Rows.Add(item.key,item.count);
                        }
                    }

功能在这里

static bool groupDate(string skill)         {             bool value = false;

            if (skill== "open")
            {
                value = true;
            }
            else
            {
                value = false;
            }

            return value;
    }

1 个答案:

答案 0 :(得分:2)

显然我们没有你的数据表可以使用,所以我从你的例子中构建了一个数组。

var lines = @"Date , Tkt Status
1/2/13    open
1/2/13    open
2/2/13    open
2/2/13    closed
2/2/13    closed
3/3/13    in-progress
4/3/13    closed".Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Skip(1).Select(l => l.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)).Select(x => new { Date = x[0], Status = x[1] }).ToArray();

然后,您可以使用这样的LINQ对其进行分组:

var grouped = lines.GroupBy(l => l.Date).Select(g => new {
    Date = g.Key,
    Open = g.Count(l => l.Status == "open"),
    Closed = g.Count(l => l.Status == "closed"),
    InProgress = g.Count(l => l.Status == "in-progress")
}).ToArray();

输出:

Date    Open Closed InProgress
1/2/13  2    0      0
2/2/13  1    2      0
3/3/13  0    0      1
4/3/13  0    1      0