Calculate fastest sum of field with where linq of datacontext - c#

I wanna transform my code:
using (DatabaseDataContext contestoDB = new DatabaseDataContext())
{
contestoDB.ObjectTrackingEnabled = false;
DateTime dataSelezionata = DateTime.Parse(data);
var elencoOre = (from db in contestoDB.Eventi
where db.DataPrenotazione.Date == dataSelezionata.Date select db);
foreach (var o in elencoOre)
oreOccupate += o.OrePreviste;
}
In this similar function for obtain sum of field with where :D :
var sum = contestoDB.Eventi.Sum(x => x.OrePreviste);
sum must be a int value...
Thanks
M.W.

Please see below:
var sum = contestoDB.Eventi
.Where(w => w.DataPrenotazione.Date == dataSelezionata.Date)
.Sum(x => x.OrePreviste);

You could just make a projection and take the sum of the projected values.
var sum = (from db in contestoDB.Eventi
where db.DataPrenotazione.Date == dataSelezionata.Date
select db.OrePreviste).Sum();
or equivalently try this:
var sum = contestoDB.Eventi
.Where(evt => evt.DataPrenotazione.Date == dataSelezionata.Date)
.Sum(evt => evt.OrePreviste);

Related

How to call a local method from the linq query

In my web api i need to execute a method from linq query itself. My linq query code snippet belongs to method is shown below which calls local method to get required data.
var onlineData = (from od in db.RTLS_ONLINEPERSONSTATUS
let zoneIds = db.RTLS_PERSONSTATUS_HISTORY.Where(p => p.person_id == od.PERSONID).OrderByDescending(z => z.stime > startOfThisDay && z.stime < DateTime.Now).Select(z => z.zone_id).ToList()
let zoneIdsArray = this.getZoneList((zoneIds.ToArray()))
let fzones = zoneIdsArray.Select(z => z).Take(5)
select new OnlineDataInfoDTO
{
P_ID = od.PERSONID,
T_ID = (int)od.TAGID,
LOCS = fzones.ToList()
}
public int[] getZoneList(decimal[] zoneIdsArray)
{
int[] zoneIds = Array.ConvertAll(zoneIdsArray, x => (int)x);
List<int> list = zoneIds.ToList();
for (int c = 1; c < zoneIdsArray.Count(); c++)
{
if (zoneIdsArray[c] == zoneIdsArray[c - 1])
{
list.Remove((int)zoneIdsArray[c]);
}
}
return list.ToArray();
}
I am getting exception at let zoneIdsArray = this.getZoneList((zoneIds.ToArray())), is there any way to solve this problem. I got logic to solve my problem from this link(Linq query to get person visited zones of current day ), the given logic is absolutely fine for my requirement but i am facing problem while executing it.
One way to achieve that would be to perform the projection on the client instead of the underlying LINQ provider. This can be done by separating your query into 2 steps:
var peopleStatus =
from od in db.RTLS_ONLINEPERSONSTATUS
let zoneIds = db.RTLS_PERSONSTATUS_HISTORY
.Where(p => p.person_id == od.PERSONID)
.OrderByDescending(z => z.stime > startOfThisDay && z.stime < DateTime.Now)
.Select(z => z.zone_id)
.ToList()
select new
{
Person = od,
ZoneIds = zoneIds,
};
var onlineData =
from od in peopleStatus.ToList()
let zoneIdsArray = this.getZoneList((od.ZoneIds.ToArray()))
let fzones = zoneIdsArray.Select(z => z).Take(5)
select new OnlineDataInfoDTO
{
P_ID = od.Person.PERSONID,
T_ID = (int)od.Person.TAGID,
LOCS = fzones.ToList()
};

How to count total of specific column in a table

I'm trying to count the Total amount of Weight in a certain column.
I've tried the following coding, but I only seem to get the first row's value and not the rest.
int QuoteId = (from x in db.Quotes where x.Id != null orderby x.Id descending select x.Id).Take(1).SingleOrDefault();
var item = db.QuoteItems.Where(x => x.QuoteId == QuoteId).First();
QuoteItemSectionGroup quoteItemList = new QuoteItemSectionGroup();
foreach (var quoteItem in db.QuoteItemSectionGroups.Where(x => x.QuoteItemId == item.Id).ToList())
{
var total = new QuoteItemSectionGroup
{
Weight = quoteItem.Weight
};
quoteItemList.Weight = total.Weight;
}
So my question is: How can I count the total amount of the Weight column in my table?
You obviously want to add the current number to the Weigth you already obtained, don´t you? Furtheremore you won´t need to create a new instance of QuoteItemSectionGroup only for the sake of setting its Weight-property temporarily.
foreach (var quoteItem in db.QuoteItemSectionGroups.Where(x => x.QuoteItemId == item.Id).ToList())
{
quoteItemList.Weight += quoteItem.Weight; // pay attention on the + before the equality-character
}
The += operator in x += 1 is simply a shortcut for x = x + 1.
Or even simpler using Linq Sum-method
var totalWeight = db.QuoteItemSectionGroups
.Where(x => x.QuoteItemId == item.Id)
.Sum(x => x.Weight);
EDIT: Furthermore you can simplify your code a bit so it finally becomes this:
var item = db.Quotes.Where(x => x.Id != null)
.OrderByDescending(x => x.Id)
.FirstOrDefault();
var totalWeight = db.QuoteItemSectionGroups
.Where(x => x.QuoteItemId == item.Id)
.Sum(x => x.Weight);

How can I calculate sum of column value in linq to sql query?

I'm write this query:
var query2 = (from p in behzad.Compare_closed_numbers_in_CRM_and_Billing_system_detail_counters
where p.fileid == point.id
select new
{
p.count
}).ToArray();
in count column have any value,and I want to sum all of the count value. For example:
how can I implant that?thanks.
If count field is int try this:
int sum = behzad.Compare_closed_numbers_in_CRM_and_Billing_system_detail_counters
.Where(t=>t.fileid == point.id)
.Select(t => t.Count ?? 0).Sum();
If count field is nvarchar(max) try this:
int sum = behzad.Compare_closed_numbers_in_CRM_and_Billing_system_detail_counters
.Where(t=>t.fileid == point.id)
.Select(t => Convert.ToInt32(t.Count)).Sum();

convert sql to linq with two tables

select ind.desc,ind.number
from int_goals_df idd, goals_df ind
where idd.dld_number = 123456
and ind.number = idd.ind_number
and ind.categorie = 2
order by follownumber
I'm having a hard time translating this to linq since it is using two tables.
I've currently solved this now imperatively with a foreach loop but not happy with it..
I'm trying to get a list of goals_df that matches with a list of int_goals_df.
Any tips would be greatly appreciated ! Thank you !
EDIT - here is the code I'm using:
//get current GoalDefinitions by selected Goal
var currentGoalDefinition = MyAppAppContext.MyAppAppContextInstance.MyAppContext.GoalDefinitions.FirstOrDefault(
d => d.DLD_GoalDFID == interv.Goal.DLD_GoalenDFID);
// get current intervGoalDefinitions by GoalDefinition
var currentintervGoalDefinitions = MyAppAppContext.MyAppAppContextInstance.MyAppContext.intervGoalDefinitions.Where(
idd => idd.DLD_GoalDFID == currentGoalDefinition.DLD_GoalDFID).OrderBy(idd => idd.IDD_VolgNummer);
intervDefinitionCollection = new ObservableCollection<intervDefinition>(MyAppAppContext.MyAppAppContextInstance.MyAppContext.intervDefinitions.Where(i => i.IND_Categorie == intCategorie));
// filter intervGoalDefinitions by intervDefinitions
var intervDefinitionCollectionTemp = new ObservableCollection<intervDefinition>();
foreach (var currentintervGoalDefinity in currentintervGoalDefinitions)
{
var foundintervGoalDefinitySorted = intervDefinitionCollection.FirstOrDefault(
i => i.IND_intervDFID == currentintervGoalDefinity.IND_intervDFID);
if (foundintervGoalDefinitySorted != null)
intervDefinitionCollectionTemp.Add(foundintervGoalDefinitySorted);
}
intervDefinitionCollection = intervDefinitionCollectionTemp;
assuming NHibernate as ORM and int_goal is a subclass of goal
var results = from idd in session.Query<IntGoals>()
where idd.DlDNumber = 123456 && idd.Category.Id == 2
orderby idd.FollowNumber
select new { idd.Description, idd.Number };
context.int_goals_df.Join(context.goals_df, x => x.ind_number, x => x.number,
(x, y) => new
{
idd = x,
ind = y
})
.Where(x => x.idd.dld_number = 123456 && x.ind.categorie = 2)
.OrderBy(x => x.idd.follownumber)
.Select(x => new
{
x.ind.desc,
x.ind.number
});
quick go - think you need the join
var results = from idd in session.Query<int_goals_df>()
join ind in session.Query<goals_df>()
on idd.ind_number equals ind.ind_number
where idd.DlDNumber = 123456 && idd.Category.Id == 2
orderby idd.FollowNumber
select new { idd.Description, idd.Number };
I tend to use the sql syntax without implicit joins
/*Fields*/
SELECT ind.desc, ind.number
/*Tables*/
FROM int_goals_df idd
INNER JOIN goals_df ind
ON ind.number = idd.ind_number
/*Conditions*/
WHERE idd.dld_number = 123456
AND ind.categorie = 2
/*Order/Grouping*/
ORDER BY follownumber
You can see from Chris's answer this translates more easily to linq.

Translating SQL to lambda with groupby

I'm trying to translate this sql statement
SELECT row, SUM(value) as VarSum, AVG(value) as VarAve, COUNT(value) as TotalCount
FROM MDNumeric
WHERE collectionid = 6 and varname in ('C3INEV1', 'C3INEVA2', 'C3INEVA3', 'C3INVA11', 'C3INVA17', 'C3INVA19')
GROUP BY row
into an EF 4 query using lambda expressions and am missing something.
I have:
sumvars = sv.staticvararraylist.Split(',');
var aavresult = _myIFR.MDNumerics
.Where(r => r.collectionid == _collid)
.Where(r => sumvars.Contains(r.varname))
.GroupBy(r1 =>r1.row)
.Select(rg =>
new
{
Row = rg.Key,
VarSum = rg.Sum(p => p.value),
VarAve = rg.Average(p => p.value),
TotalCount = rg.Count()
});
where the staticvararraylist has the string 'C3INEV1', 'C3INEVA2', 'C3INEVA3', 'C3INVA11', 'C3INVA17', 'C3INVA19' (without single quotes) and the _collid variable = 6.
While I'm getting the correct grouping, my sum, average, & count values aren't correct.
You didn't post your error message, but I suspect it's related to Contains. I've found that Any works just as well.
This should get you quite close:
var result =
from i in _myIFR.MDNumerics
where i.collectionid == _collid && sumvars.Any(v => i.varname == v)
group i by i.row into g
select new {
row = g.Key,
VarSum = g.Sum(p => p.value),
VarAve = g.Average(p => p.value),
TotalCount = g.Count()
};
Try this:
var aavresult = _myIFR.MDNumerics
.Where(r => r.collectionid == _collid && sumvars.Contains(r.varname))
.GroupBy(r1 =>r1.row,
(key,res) => new
{
Row = key,
VarSum = res.Sum(r1 => r1.value),
VarAve = res.Average(r1 => r1.value),
TotalCount = res.Count()
});

Categories

Resources