Group by sum in linq and select top

Enumerable.Sum is extension method from System.Linq namespace. It returns sum of numeric values in collection.

Sum for Numeric Types

Gets sum of values from list of integer numbers.

var numbers = new List { 8, 2, 6, 3 };int sum = numbers.Sum();

Gets sum of values from list of decimal numbers.

var numbers = new List { 8.1m, 2.2m, 6.1m, 3.3m };decimal sum = numbers.Sum();

Calling Sum on empty collection returns 0.

var numbers = new List(); int sum = numbers.Sum();

Sum for Nullable Numeric Types

Gets sum of values from list of nullable integers.

var numbers = new List { 8, 2, null, 3 };int? sum = numbers.Sum();

Returns 0 if the collection contains only null values.

var numbers = new List { null };int? sum = numbers.Sum();

Returns 0 if the collection is empty.

var numbers = new List(); int? sum = numbers.Sum();

Sum with Selector

This example sums lengths of all strings in the list.

var stringList = new List { "88888888", "22", "666666", "333" };int lengthSum = stringList.Select(x => x.Length).Sum(); int lengthSum = stringList.Sum(x => x.Length);

Sum with Query Syntax

LINQ query expression to get sum of numeric values in the collection.

var list = new List { 8, 2, 6, 3 };int sum = (from x in list select x).Sum();

LINQ query expression to get sum of numbers which match specified predicate.

var list = new List { 8, 2, 6, 3 };int sum = (from x in list where x > 4 select x).Sum();

LINQ query expression to get sum of string lengths using selector.

var list = new List { "88888888", "22", "666666", "333" };int lengthSum = (from x in list select x.Length).Sum();

Sum with Group By

This example shows how to calculate sum for each group. Lets have players. Each player belongs to a team and have a score. Team total score is sum of score of all players in the team.

var players = new List {new Player { Name = "Alex", Team = "A", Score = 10 },new Player { Name = "Anna", Team = "A", Score = 20 },new Player { Name = "Luke", Team = "L", Score = 60 },new Player { Name = "Lucy", Team = "L", Score = 40 }, };var teamTotalScores =from player in playersgroup player by player.Team into playerGroupselect new { Team = playerGroup.Key, TotalScore = playerGroup.Sum(x => x.Score), };

Sum Implementation

This is .NET Framework implementation of Enumerable.Sum method for collection of nullable numeric type (in this case IEnumerable). Note that it ignores null values (see line if (v != null) sum += v.GetValueOrDefault();).

I have linq query that extracts a summary of my sales quantities item group wise. This query causes an sql timeout. From the what i have found out, timeout indicates that my query is poorly designed and needs to be optimized.

Below is the linq query:

 (from inv in Dbcontext.tblSalesInvoices
    join det in Dbcontext.tblSalesInvoiceDetails on inv.SalesInvoiceId equals det.SalesInvoiceId
    join item in Dbcontext.tblItems on det.ItemId equals item.ItemId
    join itemGroup in Dbcontext.tblItemGroups on item.ItemGroupId equals itemGroup.ItemGroupId
    join loc in Dbcontext.tblLocations on inv.LocationId equals loc.LocationId
    where inv.InvoiceDate >= FeedSearchCriteria.FromDate && inv.InvoiceDate <= FeedSearchCriteria.ToDate
    && inv.InvoiceStatusId != Constants.REVERSED_INVOICE
    group new { det.Quantity, itemGroup.ItemGroupCode, item.Weight, item.ItemCode, det.LineTotal } by loc.LocationName into g
    select new LocationCount()
    {
    LocationName = g.Key,
    FeedBagCount = (int?)g.Where(x => x.ItemGroupCode == "FEED").Sum(x => x.Quantity),
    SupremeKg = (decimal?)g.Where(x => x.ItemGroupCode == "ABATTOIR").Sum(x => x.Weight * x.Quantity),
    SupremeValue = (decimal?)g.Where(x => x.ItemGroupCode == "ABATTOIR").Sum(x => x.LineTotal),
    DocCount = (int?)g.Where(x => x.ItemCode == "DOC").Sum(x => x.Quantity)
    }).OrderBy(x=>x.LocationName).ToListAsync();


I think my issue arises because of the where/sum clause in select. How can i re-write below query in more optimized manner.