Group by, Count and Lambda Expression

后端 未结 2 638
半阙折子戏
半阙折子戏 2020-12-29 05:51

I am trying to translate the following query:

SELECT STATE, COUNT(*)
FROM MYTABLE
GROUP BY STATE;

Into a lambda expression. I am using C# a

相关标签:
2条回答
  • 2020-12-29 06:14

    This one is good

    public IEnumerable<object> PorcentajeState(Guid id)
        {
            return _context.Sates.Where(a => a.Id == id)
                                 .GroupBy(a => a.StateId)
                                 .Select(g => new { g.Key, Count = g.Count() });
        }
    

    But try this.

    public IEnumerable<object> PorcentajeState(Guid id)
            {
                return _context.Sates.Where(a => a.Id == id)
                                     .GroupBy(a => a.StateId)
                                     .Select(g => new { g.Key.StateId, Count = g.Count() });
            }
    
    0 讨论(0)
  • 2020-12-29 06:15

    There are two issues here:

    1. The result of GroupBy will will be an enumerable of type IEnumerable<IGrouping<TKey, TSource>>. The IGrouping interface only has one property you can access, Key which is the key you specified in the GroupBy expression, and implements IEnumerable<T> so you can do other Linq operations on the result.
    2. You need to specify a property name for the anonymous type if it cannot be inferred from a property or field expression. In this case, you're calling Count on the IGrouping, so you need to specify a name for that property.

    Try this:

    public IEnumerable<object> PorcentajeState(Guid id)
    {
        return _context.Sates.Where(a => a.Id == id)
                             .GroupBy(a => a.StateId)
                             .Select(g => new { g.Key, Count = g.Count() });
    }
    

    The equivalent in query syntax would be

    public IEnumerable<object> PorcentajeState(Guid id)
    {
        return from a in _context.Sates
               where a.Id == id
               group a by a.StateId into g
               select new { a.Key, Count = g.Count() };
    }
    

    In either case, if you want the first property to be named StateId instead of Key, just change that to

    new { StateId = g.Key, Count = g.Count() }
    
    0 讨论(0)
提交回复
热议问题