LINQ获取具有字符串计数的不同列值

时间:2014-01-27 15:00:25

标签: linq c#-4.0

我在数据表中有以下数据 -

Col1       Col2
-----------------------
Pramod  |   In
Pramod  |   In
Pramod  |   Out
Pramod  |   In
Pramod  |   In
Pramod  |   Out
Pankaj  |   In
Pankaj  |   In
Pankaj  |   Out
Abhi    |   In
Abhi    |   In
Abhi    |   Out

我希望使用LINQ,

输出
Col1    | In |  Out
------------------
Pramod  | 4  |  2
Pankaj  | 2  |  1
Abhi    | 2  |  1

请帮忙

1 个答案:

答案 0 :(得分:4)

按行Col1对行进行分组,然后计算每个组中InOut值的数量:

from r in table.AsEnumerable()
group r by r.Field<string>("Col1") into g
select new {
    Col1 = g.Key,
    In = g.Count(r => r.Field<string>("Col2") == "In"),
    Out = g.Count(r => r.Field<string>("Col2") == "Out")
}