I have a LINQ-to-SQL query that runs through a table, that I want to select 3 sum's - the sums of 'Rate' and 'AdditionalCharges', so I have something like this:
var sums = from d in dc.Deliveries
where d.TripDate == DateTime.Now
select new
{
Rate = d.Rate,
AdditionalCharges = d.AdditionalCharges
};
However, obviously this returns a new row for every delivery, which means I have to sum them up afterwards - which seems fairly inefficient. Is there an easier way?
I know that this is an old question, but hey, I found it, so hopefully this will help someone else...
You can also do this using Fluent syntax:
var sums = dc.Deliveries
.Where(d => d.TripDate == DateTime.Now)
.GroupBy(d => d.TripDate)
.Select(g =>
new
{
Rate = g.Sum(s => s.Rate),
AdditionalCharges = g.Sum(s => s.AdditionalCharges)
});
Hope this helps someone...
If you use query syntax you can do something like the following
var data = dc.Deliveries.Where(d => d.TripDate == DateTime.Now)
var rateSum = data.Sum(d => d.Rate);
var additionalCharges = data.Sum(d => d.AdditionalCharges);
this is off the top of my head and not tested
Not sure but you can try out the group bye function as below
var sums = from d in dc.Deliveries
where d.TripDate == DateTime.Now
group d by new {d.Rate,d.AdditionalCharges,d.TripDate} into g
select new
{
Rate = g.Sum(s => s.Rate ),
AdditionalCharges = g.Sum(s => s.AdditionalCharges)
};
You should be able to do this:
DateTime d = DateTime.Now;
var sums = from d in dc.Deliveries
select new
{
Rate = dc.Deliveries.Where(n => n.TripDate == d).Sum(n => n.Rate),
AdditionalCharges = dc.Deliveries.Where(n => n.TripDate == d).Sum(n => n.AdditionalCharges)
};
var result = sums.FirstOrDefault();
var sums = from d in dc.Deliveries
where d.TripDate == DateTime.Now
Group by d.TripDate // or primary key
Into TotalRate = sum(d.Rate),
TotalAdditionalCharges = sum(d.AdditionalCharges)
Select TotalRate , TotalAdditionalCharges
Related
I have written a solution which basically adds missing date and sets the sales property for that date in my collection to 0 where it's missing like this:
int range = Convert.ToInt32(drange);
var groupedByDate = tr.Union(Enumerable.Range(1, Convert.ToInt32(range))
.Select(offset => new MyClassObject
{
Date = DateTime.Now.AddDays(-(range)).AddDays(offset),
Sales = 0
})).GroupBy(x => x.Date)
.Select(item => new MyClassObject
{
Sales = item.Sum(x => x.Sales),
Date = item.Key
})
.OrderBy(x => x.Date)
.ToList();
The first solution where the dates from DB were grouped by and they were missing looked like this:
var groupedByDate = tr
.GroupBy(x => x.TransactionDate.Date)
.Select(item => new MyClassObject
{
Sales = item.Sum(x => x.QuantityPurchased),
Date = item.Key.ToString("yyyy-MM-dd")
})
.OrderBy(x => x.Date)
.ToList();
I don't really like the way I did it in first solution, the code looks very messy and I honestly believe it can be written in a better manner..
Can someone help me out with this?
P.S. The first solution above that I've shown works just fine, but I would like to write something better which is more prettier to the eyes, and it looks quite messy (the first solution I wrote)...
How about generate the date range and then left join that with the result from your original query. And than set Sales to 0 when there is no match.
int range = 2;
var startDate = DateTime.Now;
var dates = Enumerable.Range(1, range)
.Select(offset => startDate.AddDays(-offset).Date);
var groupedByDate = from date in dates
join tmp in groupedByDate on date equals tmp.Date into g
from gr in g.DefaultIfEmpty()
select new MyClassObject
{
Sales = gr == null ? 0 : gr.Sales,
Date = date
};
Here is the easy way to do this:
var lookup = tr.ToLookup(x => x.TransactionDate.Date, x => x.QuantityPurchased);
var quantity = lookup[new DateTime(2017, 6, 29)].Sum();
If you want a range of dates then it's just this:
var startDate = new DateTime(2017, 6, 1)
var query =
from n in Enumerable.Range(0, 30)
let TransactionDate = startDate.AddDays(n)
select new
{
TransactionDate,
QuantityPurchases = lookup[TransactionDate].Sum(),
};
Simple.
I'm trying to create the following query in LINQ-TO-SQL.
select count(*), sum( o.CostInCents ) from Orders o
where Flag = true;
I came up with the following LINQ query:
var q = db.Orders
.Where(o => o.Flag )
var result = q
.GroupBy(o => 1)
.Select(g => new MyDTO
{
NoOfOrders = g.Count(),
TotalInCents = g.Sum(o => o.CostInCents )
})
.SingleOrDefaultAsync();
Is there a better way?
Is .GroupBy(o => 1) even OK?
The other option would be to do two queries, like below.
var q = db.Orders
.Where(o => o.Flag );
//No groupBy
var result2 = new MyDTO
{
NoOfCostedOrders = q.Count(),//hit the db
TotalInCents = q.Sum(o => o.CostInCents )//hit the db 2nd time
};
How should I judge which approach is better?
Thanks in advance!
This query can be rewritten in sql format as follows
var orderList = db.Orders.Where(o => o.Flag );
var orderSummary = from o in orderList
group o by 1 into p
select new
{
Items = p.Count(),
Total = p.Sum( x => x.CostInCents)
}
I think what you are searching for is the following slight adjustment:
var q = db.Orders
.Where(o => o.Flag).Select(o => o.CostInCents).ToList(); // hit the db here once
//No groupBy
var result2 = new MyDTO
{
NoOfCostedOrders = q.Count(), // don't hit the db
TotalInCents = q.Sum() // don't hit the db a 2nd time
};
If you have a question to my adjustment feel free to comment.
I need to return two fields using a lambda expression. The first one is the sum of the amount field and the second one is CurrentFinancial year. Below is the code that I have written, how do I include CurrentFinancialYear?
var amount = dealingContext.vw_GetContribution
.Where(o => o.ContactID == contactId)
.Sum(o => o.Amount);
return new Contribution { Amount = amount ?? 0, CurrentFinancialYear = };
Grouping by Year should do the trick:
from entry in ledger.Entries
where entry.ContactID == contactId
&& entry.Time.Year == currentFinancialYear
group entry by entry.Time.Year
into g
select new Contribution ()
{
Amount = g.ToList ().Sum (e => e.Amount),
CurrentFinancialYear = g.Key
};
UPDATE - just return the first/default result...
(from entry in ledger.Entries
where entry.ContactID == contactId
&& entry.Time.Year == currentFinancialYear
group entry by entry.Time.Year
into g
select new Contribution ()
{
Amount = g.ToList ().Sum (e => e.Amount),
CurrentFinancialYear = g.Key
}).FirstOrDefault();
First of all use a simple select
var contribution = dealingContext.vw_GetContribution
.Where(o => o.ContactID == contactId).ToList();
It will give you a list of type vw_GetContribution
Then use groupby on this list as
var groupedContribution = contribution.GroupBy(b => b.CurrentFinancialYear).ToList();
Now you can iterate through or use this list as
foreach(var obj in groupedContribution.SelectMany(result => result).ToList())
{
var amount = obj.Amount;
var Year = obj.CurrentFinancialYear;
}
OR
In single line, you can do all the above as
var contList = context.vw_GetContribution
.Select(a => new { a.Amount, a.CurrentFinancialYear })
.GroupBy(b => b.CurrentFinancialYear)
.SelectMany(result => result).ToList();
I hope this will solve your problem.
Can you try this:
var amount = dealingContext.vw_GetContribution
.Where(o => o.ContactID == contactId)
.GroupBy(o=> new { o.CurrentFinancialYear, o.Amount})
.Select(group =>
new {
year= group.Key.CurrentFinancialYear,
sum= group.Sum(x=>x.Amount)
});
Hi All i have the following code
var deptSalesQuery = from d in db.DashboardFigures
join s in outlets.Split(',').Select(x => int.Parse(x)) on d.OutletNo equals s
where (d.TypeOfinformation == "DEPTSALES")
select new DeptSales
{
Dn = (int)d.Number,
On = d.OutletNo,
Qs = (double)d.Value_4,
Se = (double)d.Value_2,
Si = (double)d.Value_3
};
What i want to do is group the query by 'Dn' which is 'd.Number'and return
the sum of (double)d.Value_4 , (double)d.Value_2 , (double)d.Value_3. I have looked on the forum and some people have asked a similar question but for some reason its not working for me. Can anyone help ?
I have changed the code to
var deptSalesQuery = from d in db.DashboardFigures
join s in outlets.Split(',').Select(x => int.Parse(x)) on d.OutletNo equals s
where (d.TypeOfinformation == "DEPTSALES")
group d by d.Number into newGroupedresult
select new DeptSales
{
Qs = (double)newGroupedresult.Sum(d => d.Value_4),
Se = (double)newGroupedresult.Sum(d => d.Value_2),
Si = (double)newGroupedresult.Sum(d => d.Value_3)
};
but its not grouping, Its showing the individual records. Also I normally have Dn = D.Number, its not allowing me to put this.
deptSalesQuery
.GroupBy(x => x.Number)
.Select(g => new
{
Dn = g.Key,
Sum = g.Sum(x => x.Value_2 + x.Value_3 + Value_4)
});
I'm trying to transform the SQL that is here http://sqlfiddle.com/#!6/a1c8d/2 in linq below. The expected result is what is in sqlfiddle, but my LINQ returns more rows.
PS: In sqlfiddle the fields are reduced to not increase pollution and stay focused on my problem.
resultado.Dados =
(
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
select new
{
a.AgendaID,
Horario = a.Horario,
Controle = a.Controle,
Cor = b.Cor,
Agenda = b.Sigla
}).AsEnumerable()
.GroupBy(g => new
{
g.AgendaID,
Horario = g.Horario.ToString("dd/MM/yyyy"),
Data = g.Horario.ToString("yyyy-MM-dd"),
g.Controle,
g.Agenda,
g.Cor
})
.Select(s => new
{
id = s.Key.AgendaID,
title = s.Key.Agenda,
start = s.Key.Data,
color = String.IsNullOrEmpty(s.Key.Cor) ? "3a87ad" : s.Key.Cor,
className = "",
someKey = 1,
allDay = false,
Resultado0 = s.Sum(m => m.Controle == "L" ? 1 : 0).ToString(),
Resultado1 = s.Sum(m => m.Controle == "B" ? 1 : 0).ToString()
});
As per the comments, this addresses the question of how to repeat your SqlFiddle in Linq. Note that the projection to a String Date cannot be converted to Sql directly, so I've had to early materialize with AsEnumerable() (obviously, in your real query, apply any filters prior to materializing!). You could probably do the grouping on just the date part using SqlFunctions, e.g. 3 x applications of SqlFunctions.DatePart will allow you to group by dd, MM and YYYY
var dados = db.AgendaHorarios1
.AsEnumerable()
.GroupBy(ah => ah.Horario.ToString("dd/MM/yyyy"))
.Select(g => new {Horario = g.Key,
Livre = g.Count(x => x.Controle == "L"),
Bloq = g.Count(x => x.Controle == "B"),
Aged = g.Count(x => x.Controle == "A")});