Get sum of two columns in one LINQ query

后端 未结 9 1000
猫巷女王i
猫巷女王i 2020-12-01 09:04

let\'s say that I have a table called Items (ID int, Done int, Total int)

I can do it by two queries:

int total = m.Items.Sum(p=>p.Total)
int done         


        
9条回答
  •  青春惊慌失措
    2020-12-01 09:17

    Figuring out where to extract the sums or other aggregate in the rest of my code confused me, until I remembered that the variable I constructed was an Iqueryable. Suppose we have a table in our database composed of Orders, and we want to produce a summary for the ABC company:

    var myResult = from g in dbcontext.Ordertable
                   group p by (p.CUSTNAME == "ABC") into q  // i.e., all of ABC company at once
                   select new
    {
        tempPrice = q.Sum( x => (x.PRICE ?? 0m) ),  // (?? makes sure we don't get back a nullable)
        tempQty = q.Sum( x => (x.QTY ?? 0m) )
    };
    

    Now the fun part -- tempPrice and tempQty aren't declared anywhere but they must be part of myResult, no? Access them as follows:

    Console.Writeline(string.Format("You ordered {0} for a total price of {1:C}",
                                     myResult.Single().tempQty,
                                     myResult.Single().tempPrice ));
    

    A number of other Queryable methods could be used as well.

提交回复
热议问题