具有两个计数的数据表的Linq c#

uubf1zoe  于 2022-12-06  发布在  C#
关注(0)|答案(2)|浏览(167)

我希望在一个查询中有两个不同的计数;我用SQL Server编写了这个程序,其中COUNT函数为

COUNT(CASE WHEN Status = 'opened' THEN 1 ELSE NULL)

返回我想要的计数。
但是,在目前的情况下,我有datatable,不确定以上两个计数在Linq中是否可行。
我的数据如下。

Email      Status 
------------------
email1     opened
email1     opened
email2     clicked
email2     clicked
email2     clicked
email1     clicked
email2     opened

输出需要:

Email      Opened      Clicked
-------------------------------
email1      2             1
email2      1             3
bttbmeg0

bttbmeg01#

使用C# Linq,请尝试以下操作:

var test =  context.stats.GroupBy(x=> x.Email).Select(groupedBy=> new {
            Email = groupedBy.FirstOrDefault().Email,
            Opened = groupedBy.Where(y=> y.Status == "opened").Count(),
            Clicked = groupedBy.Where(y=> y.Status == "clicked").Count()
        });
lmvvr0a8

lmvvr0a82#

您需要一个数据透视表。请参见下面的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication40
{
    class Program
    {

        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Email", typeof(string));
            dt.Columns.Add("Status", typeof(string));

            dt.Rows.Add(new object[] { "email1", "opened"});
            dt.Rows.Add(new object[] { "email1", "opened" });
            dt.Rows.Add(new object[] { "email2", "clicked" });
            dt.Rows.Add(new object[] { "email2", "clicked" });
            dt.Rows.Add(new object[] { "email2", "clicked" });
            dt.Rows.Add(new object[] { "email1", "clicked" });
            dt.Rows.Add(new object[] { "email2", "opened" });

            string[] statusTypes = dt.AsEnumerable().Select(x => x.Field<string>("Status")).Distinct().OrderBy(x => x).ToArray();
            var groups = dt.AsEnumerable().GroupBy(x => x.Field<string>("Email")).ToList();

            DataTable pivot = new DataTable();
            pivot.Columns.Add("Email",typeof(string));
            foreach(string statusType in statusTypes)
            {
                pivot.Columns.Add(statusType, typeof(int));
            }

            foreach(var group in groups)
            {
                DataRow row = pivot.Rows.Add();
                row["Email"] = group.Key;
                foreach(string statusType in statusTypes)
                {
                    row[statusType] = group.Where(x => x.Field<string>("Status") == statusType).Count();
                }
            }
        }
    }
}

相关问题