具有不同计数的LINQ查询

时间:2014-02-11 15:11:29

标签: c# sql linq

我正在尝试在C#中构建一个LINQ查询,该查询将为我提供一个数据集中列的不同值列表,其中包含每行的计数。结果看起来像这样。

State   Count
AL       55
AK       40
AZ       2

这是执行此操作的SQL。

SELECT name, COUNT(*) AS count
  FROM architecture arch
  GROUP BY name
  ORDER BY name

我已经找到LINQ来获取DISTINCT值。

var query = ds.Tables[0].AsEnumerable()
    .OrderBy(dr1 => dr1.Field<string>("state"))
    .Select(dr1 => new {state = dr1.Field<string>("state")})
    .Distinct().ToList();

但我无法弄清楚如何让每个不同值的COUNT(*)在LINQ中工作。知道如何将其添加到LINQ查询中吗?

7 个答案:

答案 0 :(得分:5)

您需要根据State和群组中的选择计数对结果进行分组,例如:

var query = ds.Tables[0].AsEnumerable()
            .GroupBy(r => r.Field<string>("state"))
            .Select(grp => new 
                            { 
                                state = grp.Key, 
                                Count = grp.Count()
                            })
            .OrderBy(o => o.state)
            .ToList();

答案 1 :(得分:2)

state 列的值对所有行进行分组。然后通过分组键来订购组。最后一步 - 将每个组投影到具有分组键(状态)和组中行数的匿名对象中:

var query = ds.Tables[0].AsEnumerable()
              .GroupBy(r => r.Field<string>("state"))
              .OrderBy(g => g.Key)
              .Select(g => new { State = g.Key, Count = g.Count() })
              .ToList();

查询语法看起来像(我将跳过转换为列表,以避免混合语法):

var query = from r in ds.Tables[0].AsEnumerable()
            group r by r.Field<string>("state") into g
            orderby g.Key
            select new {
                State = g.Key,
                Count = g.Count()
            };

答案 2 :(得分:1)

为什么要使用Distinct,当您几乎可以逐字逐句地将SQL查询转换为LINQ时?你可以这样做:

var query = ds.Tables[0].AsEnumerable()
    .GroupBy(dr1 => dr1.Field<string>("state"))
    .Select(g => new {
        State = g.Key
    ,   Count = g.Count()
    })
    .OrderBy(p => p.State)
    .ToList();

这会生成{State, Count}对的列表。如果您更喜欢状态计数字典,可以像这样更改查询:

var query = ds.Tables[0].AsEnumerable()
    .GroupBy(dr1 => dr1.Field<string>("state"))
    .ToDictionary(g => g.Key, g => g.Count());

答案 3 :(得分:1)

我认为你需要GroupBy

var query = ds.Tables[0].AsEnumerable()
              .GroupBy(dr1 => dr1.Field<string>("state"))
              .Select(g => new {state = g.Key, count = g.Count())
              .ToList();

答案 4 :(得分:0)

var query = ds.Tables[0].AsEnumerable()
              .GroupBy(x=>x.Field<string>("state"))
              .Select( g => new{
                   state = g.Key,
                   count = g.Count()
              });

答案 5 :(得分:0)

猜猜是什么,等同于group by group by:)

        var query = from dr1 in ds.Tables[0].AsEnumerable()
                    group dr1 by dr1.Field<string>("state") into state
                    select new { State = state.Key, Count = state.Count() };

答案 6 :(得分:0)

var stat = from row in ds.Tables[0].AsEnumerable()
group row by new
{
  Col1 = row["Name"],
} into TotalCount
select new
{
  ActionName = TotalCount.Key.Col1,
  ActionCount = TotalCount.Count(),
 };