Sum of a specific column using LINQ

Using the following query, I get all the values ​​for the column called promotionValue . I want to get the sum of all the values ​​* that match *

var matched = from table1 in dvtempPropertyRoomRatePromotion.ToTable().AsEnumerable()
              join table2 in dvPropertyRooms.ToTable().AsEnumerable() on
              table1.Field<DateTime>("RateDate") equals table2.Field<DateTime>("RateDate")
            where table1.Field<DateTime>("RateDate") == table2.Field<DateTime>("RateDate")
               select table1.Field<string>("promotionValue");

      

+3


source to share


3 answers


You need to parse the string, int

or decimal

:

var matched = from r1 in dvtempPropertyRoomRatePromotion.ToTable().AsEnumerable()
              join r2 in dvPropertyRooms.ToTable().AsEnumerable() 
              on r1.Field<DateTime>("RateDate").Date equals r2.Field<DateTime>("RateDate").Date
              select decimal.Parse(r1.Field<string>("promotionValue"));
decimal sum = matched.Sum();

      

Note that I also changed some other things like redundant where

(since you've already joined these tables) or property Date

DateTime

.



Besides,

  • Why is it needed at all DataView

    ? ToTable

    always creates a new one DataTable

    . Why don't you use it Linq-To-DataSet

    for everyone? I assume you used DataView

    to filter, use instead Enumerable.Where

    . It would be more consistent, more efficient, and more readable.
  • Why promotionValue

    does the column contain a row? You must store it as a numeric type.
+4


source


Here I am putting a simple query for the sum of two columns in a table.

SELECT res.Date, res.Cost, res.Cost + res_con.Cost FROM [ExpenseMst] res inner join [ExpenseMst_2] res_con on res_con.ID = res.ID

Date | cost 1 | cost 2 | General

2014-03-04 | 5200 | 5200 | 10400

2014-03-04 | 5012 | 5012 | 10024



2014-03-22 | 100 | 100 | 200

2014-03-13 | 25 | 25 | 50

2014-02-22 | 120 | 120 | 240

Hope this is helpful. :)

0


source


You can do

int sum = 0;
foreach(int match in matched)
{
  sum = sum + match;
}

      

-2


source







All Articles