Reputation: 109
the tableis this:
The function in linq is this:
public int CalcolaOreOccupate(string data)
{
int oreOccupate = 0;
if (String.IsNullOrEmpty(data))
{
using (DatabaseDataContext contestoDB = new DatabaseDataContext())
{
contestoDB.ObjectTrackingEnabled = false;
var elencoOre = (from db in contestoDB.Eventi
where db.DataPrenotazione.Date == DateTime.Now.Date
select db);
foreach (var o in elencoOre)
{
oreOccupate += o.OrePreviste;
}
}
}
else
{
/* ... othere code ... */
}
return oreOccupate;
}
oreOccupate is sum of OrePreviste. I wanna get better function of mine. How can i do with linq? Thanks
Upvotes: 3
Views: 359
Reputation: 12491
Just use Sum()
extension method:
var nowDate = DateTime.Now.Date;
oreOccupate = contestoDB.Eventi
.Where(x => x.DataPrenotazione.Date == nowDate)
.Select(x => x.OrePreviste)
.DefaultIfEmpty(0)
.Sum();
When you do it like you show you basically get all your data from DB to your server to process and if you using MS SQL you can translate your query like i show to make all calculations in your Data base using LinqToSQL
As @enigmativity point in comments there is no need to init DateTime.Now.Date
in separate variable since you using linqtosql and it will be translated to sql statement so called just once.
Upvotes: 4