C# Linq Grouping

前端 未结 2 1169
面向向阳花
面向向阳花 2021-01-01 16:40

I\'m experimenting with Linq and am having trouble figuring out grouping. I\'ve gone through several tutorials but for some reason can\'t figure this out.

As an exam

相关标签:
2条回答
  • 2021-01-01 17:00

    Actually, although Thomas' code will work, it is more succint to use a lambda expression:

    var totals =
    from s in sites
    group s by s.SiteID into grouped
    select new
    {
        SiteID = grouped.Key,
        Last30Sum = grouped.Sum( s => s.Last30 )
    };
    

    which uses the Sum extension method without the need for a nested LINQ operation.

    as per the LINQ 101 examples - http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#sumGrouped

    0 讨论(0)
  • 2021-01-01 17:18

    Easiest way for me to illustrate is using in-memory objects so it's clear what's happening. LINQ to SQL should be able to take that same LINQ query and translate it into appropriate SQL.

    public class Site
    {
        static void Main()
        {
            List<Site> sites = new List<Site>()
            {
                new Site() { SiteID = 1, VisitorType = 1, Last30 = 10, Total = 100, },
                new Site() { SiteID = 1, VisitorType = 2, Last30 = 40, Total = 140, },
                new Site() { SiteID = 2, VisitorType = 1, Last30 = 20, Total = 180, },
            };
    
            var totals =
                from s in sites
                group s by s.SiteID into grouped
                select new
                {
                    SiteID = grouped.Key,
                    Last30Sum = 
                        (from value in grouped
                         select value.Last30).Sum(),
                };
    
            foreach (var total in totals)
            {
                Console.WriteLine("Site: {0}, Last30Sum: {1}", total.SiteID, total.Last30Sum);
            }
        }
    
        public int SiteID { get; set; }
        public int VisitorType { get; set; }
        public int Last30 { get; set; }
        public int Total { get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题