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) });
Related
I plan on using this in a subquery but can't figure out the correct syntax to translate the following query into LINQ:
select ChapterID, min(MeetingDate)
from ChapterMeeting
group by ChapterID
var query = myDataContext.ChapterMeeting
.GroupBy(cm => cm.ChapterID)
.Select(g => new {
g.Key,
MinMeetingDate = g.Min(cm => cm.MeetingDate)
});
Well, Amy beat me to it, but in case you wanted to see it with the "comprehension" syntax:
var q = (
from cm in context.ChapterMeeting
group cm by cm.ChapterID into cmg
select new {
ChapterID = cmg.Key,
FirstMeetingDate = cmg.Min(cm => cm.MeetingDate)});
Can someone help me convert a SQL to Linq? I'm new to Linq and could use some help....
My SQL query string is;
SELECT *, Sum(RequisitionQTY*RequisitionPrice) as Total
FROM partrequisition
WHERE ReferenceNumber = searchModel.ReferenceNumber
GROUP BY 'ReferenceNumber'
what I have gotten so far is
var result = db.partrequisition
.Where(c => c.ReferenceNumber == searchModel.ReferenceNumber)
.GroupBy(c => c.ReferenceNumber)
.Select( <??> );
Not understanding how to do the calculation and build that into the Linq..
Thank you...
Like this? The result will be a list of sum for each reference numberger
var result = db.partrequisition
.Where(c => c.ReferenceNumber == searchModel.ReferenceNumber)
.GroupBy(c => c.ReferenceNumber)
// For each group, calculate the sum
.Select(g=> g.Sum( item=>item.RequisitionQTY*item.RequisitionPrice ))
.ToList();
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();
I have a table "Book" with a many-to-many relationship to "Tag" and need a distinct Book-count pr. Tag. In SQL, the query looks like this:
SELECT t.NAME,
count(DISTINCT b.BookId)
FROM _Tag t
JOIN Book.BookTag bt
ON t.Id = bt.TagId
JOIN Books b
ON b.BookId = bt.BookId
GROUP BY t.NAME
ORDER BY count(DISTINCT b.BookId) DESC;
I have fetched the tags and included the Books navigation-property and from this I should be able to get distinct BookId's pr. tagname. I want to get the result in a tuple.
So far I have tried the following:
var tagTuples = from tag in tags
join book in tags.Select(t => t.Books) on tag.Books equals book
group new {tag, book} by tag.Name
into g
select new Tuple<string, string, int>("tags", g.Key, g.Select(x => x.book).Count());
...and...
var tagTuples = tags.GroupBy(t => t.Name)
.Select(t2 => new Tuple<string, string, int>("tags", t2.Key, t2.Sum(t4 => t4.Books
.Select(b => b.BookId).Distinct().Count())))
.Where(t3 => !string.IsNullOrWhiteSpace(t3.Item2)).Take(15);
...and my latest version:
var tagTuples =
tags.Select(t => new {t.Name, BookId = t.Books.Select(b => b.BookId)})
.GroupBy(tb => tb.Name)
.Select(tb2 => new Tuple<string, string, int>("tags", tb2.Key, tb2.Sum(tb3 => tb3.BookId.Distinct().Count())));
Nevermind the small differences in the query's - I'm only interested in a solution to the problem described above.
Frustration! It takes me 2 minutes to write an SQL query that does this and I'm pretty sure there's a simple answer, but I lack EF routine.
Thankyou for your time. :)
using(var ctx = new EntitiesContext())
{
// GROUP By name
var bookCountByTag = ctx.Tags.GroupBy(t => t.Name)
.Select(t2 => new {
// SELECT the key (tag name)
t2.Key,
// "GroupBy" has many result, so use SelectMany
Count = t2.SelectMany(t3 => t3.book)
.Distinct()
.Count()})
.ToList();
}
i have a LINQ Query which is written in VB.NET:
foo = (From p In lOrder
Group By p.ItemCode Into Group = Sum(p.Quantity)
).ToDictionary(Function(x) x.ItemCode, Function(x) x.Group)
My problem is to translate the Sum. C# seems to not like it very well.
Can anybody help me translating this query?
thank you
Here's an exact translation of your LINQ query in C#:
var foo = lOrder.GroupBy(p => p.ItemCode,
(key, values) => new
{
ItemCode = key,
Group = values.Sum(v => v.Quantity)
})
.ToDictionary(x => x.ItemCode, x => x.Group);
If I understand correctly, you want to get a mapping between the item code to the cumulative quantity of the items under this code.
Given an IEnumerable named orders you can do the following:
var foo = from p in orders
group p by p.ItemCode into OrderGroupedByCode
select new { Code = OrderGroupedByCode.Key, Sum = OrderGroupedByCode.Sum(x => x.Quentity) };
This gives you an IEnumerable of anonymous objects the you can easily turn into a dictionaryif you want:
foo.ToDictionary(x => x.Code, x => x.Sum)