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");
source to share
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 oneDataTable
. Why don't you use itLinq-To-DataSet
for everyone? I assume you usedDataView
to filter, use insteadEnumerable.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.
source to share
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. :)
source to share