Search code examples
c#linqobject-reference

How to sum a field on linq that has a where clause which pulls data that returns nulls too?


I have a LINQ query, which groups by the company's Warehouse descriptions. Now, I had to sum the items' weight for the month. But then I have another field, which sums the total weight of scrap, which is found by a field that that contains the word "SCRP". I get the infamous object reference error is not set to an instance of an object error when I do this. I assume it's because there are nulls or something. The field contains other values or nulls.

This is the query that I have. It runs perfectly until I try to add the UserSequence bit:

P.s the scrap percentage doesn't work either, but I assume this is because of the same issue.

var fistDayofPreviousMonth = DateTime.Today.AddMonths(-4);
var testScrapQuery = from s in mapicsSession.Query<InventoryHistory>()
                     where s.PostedTimestamp > fistDayofPreviousMonth
                     orderby s.Warehouse.Description
                     group s by s.Warehouse.Description
                     into test
                     let tw = mapicsSession.Query<InventoryHistory>()
                         .Where(x => x.Warehouse.Description == test.Key)
                         .Sum(x => x.Item.Weight)
                     let sw = mapicsSession.Query<InventoryHistory>()
                         .Where(x => x.Warehouse.Description == test.Key 
                                     && x.UserSequence == "SCRP")
                         .Sum(x => x.Item.Weight)
                     select new
                     {
                         Warehouse = test.Key,
                         TotalWeight = tw,
                         ScrapWeight = sw
                         //ScrapPercentage = (sw / tw) * 100
                     };

Solution

  • You can fix the first issue by coalescing the value (now it takes 0 as a value if x or x.Item is null):

    .Sum(x => x?.Item?.Weight ?? 0)
    

    Or with an additional Where:

    .Where(x => x != null && x.Item != null)
    .Sum(x => x.Item.Weight)
    

    And I guess this could do for your percentage calculation (prevent division by 0):

    ScrapPercentage = tw == 0 ? 100 : (sw / tw) * 100