简体   繁体   English

将以下SQL计数等效于LINQ计数

[英]Equivalent of the following SQL Count to LINQ Count

i have some problem with LINQ, my problem is similar to the example below, I have a table named History with the following data 我的LINQ有问题,我的问题类似于下面的示例,我有一个名为History的表,其中包含以下数据

Method DateUsed

A      2013/02/01
A      2013/01/01
B      2013/01/01
B      2012/01/01 <--
C      2013/01/01
C      2012/02/01

what i want is to get the number or the count of methods that were used in a specific year, if i want to get the year =2013 the result would be: 我想要的是获取特定年份使用的方法的数量或计数,如果我想要获取的年份= 2013,结果将是:

Method Total 

A       2
B       1 <--
C       3

in SQL my query would be something like 在SQL我的查询将是这样的

Select Method, Count(DateUsed) as Total from history 
where YEAR(DateUsed) = '2013' group by Method 

however, i can't figure out how to do it in LINQ, can someone help me with the LINQ equivalent? 但是,我不知道如何在LINQ中做到这一点,有人可以用LINQ等效产品帮助我吗?

thanks in advance 提前致谢

You ll use a query similar as your SQL for LINQ. 您将使用与SQL相似的查询LINQ。 Group by Method and then select the method and count. 按方法分组,然后选择方法和计数。

var result = History.Where(H=>H.DateUsed.Year == 2013)
                    .GroupBy(g => g.Method)
                    .Select(g => new {Method = g.Key, Count = g.Count()});

If you're in linq to entities, you'll need SqlFunctions . 如果您对实体不满意 ,则需要SqlFunctions

var result = context.History
                    //linq to entities
                    .Where(m => SqlFunctions.DatePart("year", DateUsed) == 2013)
                    //linq to object
                    .Where(m => m.DateUsed.Year == 2013)
                    //common part
                    .GroupBy(m => m.Method)
                    .Select(g => new {
                        Method = g.Key,
                        Total = g.Count()
                    });

The other answers are correct, this one just makes use of the LINQ query syntax: 其他答案是正确的,这只是利用LINQ查询语法:

var result = 
    from m in context.History
    where m.DateUsed.Year == 2013
    /* or where SqlFunctions.DatePart( "YEAR", m.DateUsed ) == 2013 */
    group m by m.Year into g
    select new { Method = g.Key, Total = g.Count() };

I find that the query syntax is easier to use in some circumstances, and that the LINQ extension methods are easier to use in others. 我发现查询语法在某些情况下更易于使用,而LINQ扩展方法在其他情况下更易于使用。 It helps to be familiar with both. 熟悉两者都有助于。

Note: not tested 注意:未测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM