Name issue_date free_coupon_days category
Einstein 25/Dec/2015 60 movie
Hellen Keller 01/Jan/2016 7 movie
Einstein 09/Jul/1999 9 movie
Einstein 14/Jun/2015 3 waterpark
Hellen Keller 19/Nov/1980 30 movie
Einstein 29/Sep/2015 19 movie
I have a DataTable dt, for example.
And I want to sum free_coupon_days with criteria as 'Eienstein', Date between '27/Sep/2015 ~ 27/Dec/2015', 'movie'.
The desirable output is 79 as calculated the rows as below.
Name issue_date free_coupon_days category
Einstein 25/Dec/2015 60 movie
Einstein 29/Sep/2015 19 movie
I've tried some ways, but I'm beginner against complicated conditions.
This is some of the code I tried:
int sum_freecoupon_days_between_dates = (from item in dt
where item.issue_date >= '27/Sep/2015' && item.issue_date <= '27/Dec/2015' &&
item.Name == "Einstein" &&
item.category == "movie"
select item).Sum(k => k.free_coupon_days);
How can I do this in LINQ ?
I share my solution:
int sum = dt.AsEnumerable().Where(dr => dr.Field<string>("Name") == "Einstein" &&
dr.Field<string>("category") == "movie" &&
(dr.Field<DateTime>("issue_date").Date >= Convert.ToDateTime("27/09/2015") && dr.Field<DateTime>("issue_date").Date <= Convert.ToDateTime("27/12/2015"))).
Select(dr => dr.Field<int>("free_coupon_days")).
Sum();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments