linq is taking long to order by datediff - c#

I am trying to convert the following sql query to linq. The sql query is taking one second to run, but the linq is taking about 10 seconds
to return the results. Could anyone please let me know how can I reduce the time on linq query
select datediff(mm, min(QueuedTime), max(QueuedTime)), SequencingQueue
from tbl_AS_MessageQueue with (nolock)
group by SequencingQueue
order by datediff(mm, min(QueuedTime), max(QueuedTime)) desc
var longRunningQueries = context.TblMessageQueues.GroupBy(x => x.SequencingQueue).Select(g => new TblMessageQueueDto
{
DateDiff = DbFunctions.DiffMonths(g.Min(x => x.QueuedTime),
g.Max(x => x.QueuedTime)),
SequencingQueue = g.Key
}).OrderByDescending(a => a.DateDiff).ToList();

Rewrite your query to select DTO after ordering:
var longRunningQueries = context.TblMessageQueues
.GroupBy(x => x.SequencingQueue)
.Select(g => new {
DateDiff = DbFunctions.DiffMonths(g.Min(x => x.QueuedTime), g.Max(x => x.QueuedTime)),
SequencingQueue = g.Key
}).OrderByDescending(a => a.DateDiff)
.Select(t => new TblMessageQueueDto {
DateDiff = t.DateDiff,
SequencingQueue = t.SequencingQueue
}).ToList();

Related

I didn't true use order by in linq

Hi i develop web app with c#. I have sql query and i convert to linq but it's not working true because of order by
My sql query
Select TOP 3 HastalikIsmi From Hastaliklar group by HastalikIsmi order by Count(*) desc
My linq
public List<HastalikDto> GetHastalikDto()
{
using (SirketDBContext context = new SirketDBContext())
{
var result = from hastalik in context.Hastaliklar
group hastalik by hastalik.HastalikIsmi into isim
select new HastalikDto { HastalikIsmi = isim.Key };
return result.OrderBy(h => h.HastalikIsmi).Take(3).ToList();
}
}
Here's how you can do the order by on the count of each group and take the 3 with the highest count.
var result = context.Hastaliklar
.GroupBy(x => x.HastalikIsmi)
.OrderByDescending(grp => grp.Count())
.Select(grp => grp.Key)
.Take(3)
.ToList();

Order by and group by and sum using SQL

What I am trying to do is get the top 10 most sold Vegetables by grouping them by an Id passed by parameter in a function and ordering them by the sum of their Quantity. I don't know how to use SUM or (total) quite yet but I thought I'd post it here seeking help. If you need me offering you anything else I will be ready.
This is my code:
TheVegLinQDataContext db = new TheVegLinQDataContext();
var query =db.OrderDetails.GroupBy(p => p.VegID)
.Select(g => g.OrderByDescending(p => p.Quantity)
.FirstOrDefault()).Take(10);
And this is an image of my database diagram
Group orders by Vegetable ID, then from each group select data you want and total quantity:
var query = db.OrderDetails
.GroupBy(od => od.VegID)
.Select(g => new {
VegID = g.Key,
Vegetable = g.First().Vegetable, // if you have navigation property
Total = g.Sum(od => od.Quantity)
})
.OrderByDescending(x => x.Total)
.Select(x => x.Vegetable) // remove if you want totals
.Take(10);
Since this is not clear that you are passing what type of id as function parameter, I'm assuming you are passing orderId as parameter.
First apply where conditions then group the result set after that order by Total sold Quantity then apply Take
LINQ query
var result = (from a in orderdetails
where a.OrderId == orderId //apply where condition as per your needs
group a by new { a.VegId } into group1
select new
{
group1.Key.VegId,
TotalQuantity = group1.Sum(x => x.Quantity),
group1.FirstOrDefault().Vegitable
}).OrderByDescending(a => a.TotalQuantity).Take(10);
Lamda (Method) Syntax
var result1 = orderdetails
//.Where(a => a.OrderId == 1) or just remove where if you don't need to filter
.GroupBy(x => x.VegId)
.Select(x => new
{
VegId = x.Key,
x.FirstOrDefault().Vegitable,
TotalQuantity = x.Sum(a => a.Quantity)
}).OrderByDescending(x => x.TotalQuantity).Take(10);

How to convert this SQL statement to Linq for C#

I am trying to convert my simple SQL statement into Linq format for my C# application but I always seem to struggle making the conversion. I downloaded linqpad and have been playing around with it but I'm still having issues with the proper format.
My SQL statement:
SELECT distinct PictureCity, PictureState
FROM Website_Gallery
GROUP BY PictureCity, PictureState, PictureDate
ORDER BY PictureCity, PictureState
The results are ordered by PictureCity and look like this:
Abington MA
Acton MA
Acushnet MA
Agawam MA
Andover MA
Arlington MA
Arlington TX
Ashby MA
Ashland MA
What I have so far in my C# application which I can't seem to get to work. (I suck at linq).
var Results = _context.Website_Gallery
.(g => g.PictureCity, g => g.PictureState).AsEnumerable()
.Select g
.GroupBy(g => g)
Seems like all you need is
var results = _context.Website_Gallery
.OrderBy(x => x.PictureCity)
.ThenBy(x => x.PictureState)
.Select(x => new { x.PictureCity, x.PictureState })
.Distinct();
that would be equivalent to the following SQL
SELECT distinct PictureCity, PictureState
FROM Website_Gallery
ORDER BY PictureCity, PictureState
because what you had did not need the group by
Note you can then either iterate that result in a foreach or tack a ToList to the end to materialize the query into memory.
SQL
SELECT distinct PictureCity, PictureState
FROM Website_Gallery
ORDER BY PictureCity, PictureState
Linq
var Results = _context.Website_Gallery
.Select(g => new { g.PictureCity, g.PictureState })
.Orderby(p => p.PictureCity).ThenBy(p => p.PictureState)
.Distinct().ToList();
Or you can also do this
var Results = _context.Website_Gallery
.GroupBy(x => new { PictureCity = x.PictureCity, PictureState = x.PictureState })
.Select(g => new { g.Key.PictureCity, g.Key.PictureState }).Orderby(p => p.PictureCity).ThenBy(p => p.PictureState)
.ToList();

Lambda Group By Max

I have this query.
select distinct game_id, max(event_number) as LatestEvent from Source group by game_id
But I would like this converted to its Linq or Lambda equivalent and I havent found a way to do so properly. Can someone advise.
Thanks for your time.
var q = db.Table
.GroupBy(x => x.game_id)
.Select(g => new { game_id = g.Key, LatestEvent = g.Max(x => x.event_number) });

How to create query of queries using LINQ?

I'm trying to convert query of queries used in ColdFusion to LINQ and C#. The data come from data files, rather than from the database.
I converted the first query, but have no clue as to
how to use it to query the second query.
how to include count(PDate) as DayCount in the second query.
Below is the code using query of queries in ColdFusion:
First query
<cfquery name="qSorted" dbtype = "query">
SELECT OA, CD,PDate,
FROM dataQuery
GROUP BY CD,OA,PDate,
</cfquery>
Second query
<cfquery name="qDayCount" dbtype = "query">
SELECT OA, CD, count(PDate) as DayCount
FROM qSorted // qSorted is from the first query.
GROUP BY
OA, CD
ORDER BY
OA, CD
</cfquery>
Here's the first converted LINQ query, and it works fine:
var Rows = allData.SelectMany(u => u._rows.Select(t => new
{
OA = t[4],
CD = t[5],
PDate = t[0]
}))
.GroupBy(x => new { x.CD, x.OA, x.PDate })
.Select(g => new
{
g.Key.OA,
g.Key.CD,
g.Key.PDate
})
.ToList();
Here's the pseudo-code for the second LINQ query, which I need your assistance:
var RowsDayCount = Rows //Is this correct? If not, how to do it?
.GroupBy(x => new { x.OA, x.PDate, x.CD, })
.Select(g => new
{
g.Key.OA,
g.Key.CD,
g.Key.PDate,//PDate should be PDate.Distinct().Count() asDayCount
// See DayCount in cfquery name="qDayCount" above.
})
.OrderBy(u => u.OA)
.ThenBy(u => u.CD)
.ToList();
Your second query origionally wasn't grouping on PDate, but your translation is. That's wrong. If you want to count the number of PDates for each OA/CD pair, you need to not group on PDate. Once you've made that change, you can modify the Select to pull out all of the PDate values from the group, and count the distinct values.
.GroupBy(x => new { x.OA, x.CD, })
.Select(g => new
{
g.Key.OA,
g.Key.CD,
DayCount = g.Select(item => item.PDate).Distinct().Count(),
})

Categories