Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of a particular column using LINQ

Tags:

c#

linq

Using the below mentioned query I am getting the all the values of a column called promotionValue . I want to get the sum of all the values of *matched *

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");
like image 449
palak mehta Avatar asked Dec 20 '25 02:12

palak mehta


1 Answers

You need to parse the string to 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've also changed some other things like the redundant where (since you've already joined these tables) or the Date property of DateTime.

Apart from that

  1. why do you need the DataView at all? ToTable creates always a new DataTable. Why don't you use Linq-To-DataSet for all? I assume you've used the DataView for filtering, use Enumerable.Where instead. That would be more consistent, more efficient and more readable.
  2. why is the column promotionValue a string? You should store it as a numeric type.
like image 97
Tim Schmelter Avatar answered Dec 22 '25 15:12

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!