Guy's I need a Lambda expression for this sql statement.
select GalleryId, Max(Bid)
from BidModels
where GalleryId in (select GalleryId from BidModels where UserId = (UserId))
group by GalleryId
I don't see why you need the subquery, given that you can just select all Bids where UserId = userid being passed in. With that in mind:
var userid = <whatever>;
var query = from b in BidModels
where b.UserId = userid
group by b.GalleryId into g
select new {Id = g.Key, MaxBid = g.Max(x => x.Bid)};
Here is how you can do it
var galleryIds = (bidModelses.Where(b => b.UserId == [YOURPARAMETER])
.Select(b => b.GalleryId));
var query = (bidModelses.Where(bm => galleryIds.Contains(bm.GalleryId))
.GroupBy(bm => bm.GalleryId)
.Select(gbm => new {gbm.Key, MaxBid = gbm.Max(p => p.BidId)}));
This seems to be the answer thanks for the help:
from b in BidModels
let MyGallery = from a in BidModels where a.UserId == (1) select new { a.GalleryId }
where MyGallery.Any()
group b.Bid by b.GalleryId into g
select new
{ Id = g.Key,
MaxBid = g.Max()
}
Related
I have a table with products that can be in different locations to be submited to a rework task, but i need to pick only the most recent one based on the product.
I have the following table:
ID Tag Location task Date
1 1 A T1 2016/06/01
2 1 B T1 2016/07/01
3 2 A T1 2016/06/01
4 2 A T2 2016/07/01
i ned the select the row of the Tags with most recent Date to have in output the row with ID 2 and ID 4.
What is the correct linq query for that?
First group by tag then select max date
var result = db.Table.GroupBy(i => i.Tag).Select(i => new
{
Tag = i.Key,
Date = i.Max(t => t.Date)
}).ToList();
Updated 1 (Comment 1)
var result = (from x in db.Table
join z in (db.Table.GroupBy(i => i.Tag).Select(i => new
{
Tag = i.Key,
Date = i.Max(t => t.Date)
})
) on new { A = x.Tag, B = x.Date} equals { A = z.Tag, B = z.Date }
select x).ToList();
Update 2 (Comment 2)
var result = (from x in db.Table
join z in (db.Table.GroupBy(i => new { i.Tag, i.Task }).Select(i => new
{
Tag = i.Key.Tag,
Task = i.Key.Task,
Date = i.Max(t => t.Date)
})
) on new { A = x.Tag, B = x.Date, C = x.Task} equals { A = z.Tag, B = z.Date, C = z.Task }
select x).ToList();
I have two tables.First is CompetitionUsers and Competitionpoints.
There is foreign key relationship between tables with ParticipateID.
In CompetitionPoints Table there are points different points for multiple participateID.So I want to fetch Total Points and the Rank based on total points.So if there is multiple same total points for one participateID, the rank for that participateid should be same .Its same like student Total marks and Rank from that Mark.
Here is my code.
var competitionusers = (from c in db.CompetitionUsers
group c by new { c.ParicipateId, c.CompetitionPoints.FirstOrDefault().Points }
into g orderby g.Key.Points descending select
new { Points = db.CompetitionPoints.Where
(x => x.ParticiapteId == g.FirstOrDefault().ParicipateId).Sum(x => x.Points),
Rank = (from o in db.CompetitionUsers
group o by o.CompetitionPoints.FirstOrDefault().Points into l
select l).Count(s => s.Key > db.CompetitionPoints.
Where(x => x.ParticiapteId == g.FirstOrDefault().ParicipateId).Sum(x => x.Points)) + 1,
}).Where(x => x.Points != null).OrderByDescending(x => x.Points).AsQueryable();
If I understand your data model correctly, I think you could simplify to something like this:
var result = db.CompetitionUsers
// group by total points
.GroupBy(cu => cu.CompetitionPoints.Sum(cp => cp.Points))
// order by total points descending
.OrderByDescending(g => g.Key)
// calculate rank based on position in grouped results
.SelectMany((g, i) => g.Select(cu => new { Rank = i+1, TotalPoints = g.Key, CompetitionUser = cu }));
IQueryable<CompetitionLaderMadel> competitionUsers;
competitionUsers = (from c in db.CompetitionUsers
select new CompetitionLaderMadel
{
CompetitionName = c.Competition.CompetitionName,
CompetitionId = c.CompetitionId,
Points = db.CompetitionPoints.Where(x => x.ParticiapteId == c.ParicipateId).Sum(x => x.Points),
IsFollow = db.CrowdMember.Any(x => x.Following == userid && x.UserCrowd.UserID == c.UserId && x.Status != Constants.Deleted),
}).Where(x => x.Points != null && x.UserId != null).OrderByDescending(x => x.Points);
And then Wrote this Query
var q = from s in competitionUsers
orderby s.Points descending
select new
{
CompetitionName = s.CompetitionName,
CompetitionId = s.CompetitionId,
HeadLine = s.HeadLine,
UserId = s.UserId,
Points = s.Points,
Image = s.Image,
IsFollow = s.IsFollow,
UserName = s.UserName,
Rank = (from o in competitionUsers
where o.Points > s.Points
select o).Count() + 1
};
I have a working sql statement and want it as linq statement or linq methode chain.
My statement is:
SELECT T1.*
FROM (SELECT Col1, MAX(InsertDate) as Data
FROM Zugbewegungsdaten
GROUP BY Loknummer) as temp JOIN T1
ON (T1.Col1= temp.Col1
AND Zugbewegungsdaten.InsertDate= temp.Date)
WHERE Col3=1
ORDER BY Loknummer
Can anybody help me to translate it?
Edit after comment:
Ok, my result for the inner select:
var maxResult = (from data in context.T1
group data by data.Col1
into groups
select new
{
Train = groups.Key,
InsertDate= groups.Max( arg => arg.InsertDate)
}) ;
I tried the join like this:
var joinedResult = from data in context.T1
join gdata in maxResult on new
{
data.Col1,
data.InsertDate
}
equals new
{
gdata.Col1,
gdata.InsertDate
}
select data;
But i get a compiler error by the join that the typeargument are invalid.
In the case that the join works i whould use a where to filter the joinedResult.
var result = from data in joinedResult
where data.Col3 == true
select data;
After much more "try and error", I got this version it looks like it works.
var joinedResult = ( ( from data in context.T1
group data by data.Col1
into g
select new
{
Key= g.Key,
Date = g.Max( p => p.InsertDate)
} ) ).Join( context.T1,
temp => new
{
Key = temp.Key,
InsertDate = temp.Date
},
data => new
{
Key = data.Col1,
InsertDate = data.InsertDate
},
( temp,
data ) => new
{
temp,
data
} )
.Where( arg => arg.data.Col3)
.OrderBy( arg => arg.data.Col1)
.Select( arg => arg.data );
Could it be that i have to set the same property names (Key, InsertDate) by joins over multi columns?
I'm pretty stuck on converting this to LINQ:
SELECT
COUNT(1) AS Registrations,
YEAR(Join_date) AS Year,
MONTH(Join_date) AS Month
FROM tblForumAuthor
GROUP BY YEAR(Join_date), MONTH(Join_date)
ORDER BY Year, Month
It's just a simple report, but I can't work out how to do the group by's and counts as the select new. I've only managed this pathetic attempt:
var q = (from c in db.tblForumAuthors
select new {Year = c.Join_date.Year,
Month = c.Join_date.Month,
Registrations = });
var results = db.tblForumAuthors.GroupBy(r => new {Year = r.Join_date.Year, Month = r.Join_date.Month})
.Select(g => new {Registrations = g.Count(), g.Key.Year, g.Key.Month})
.OrderBy(r => r.Year)
.ThenBy(r => r.Month)
from c in db.tblForumAuthors
group c by new {month = t.Join_Date.Month, year = t.Join_Date.Year}
into g select new {month = g.Key.month, year = g.Key.year, count = g.Count()}
Pipped to the post.... but this should do the trick. Notice how you can group by multiple fields by using an anonymous type. The properties of the group are available through the Key property of the grouping. Not sure if this will produce Count(1), though. IIRC it will be Count(*).
from c in db.tblForumAuthors
group c by new { c.Join_date.Year, c.Join_date.Month } into g
orderby g.Year, g.Month
select new {
Registrations = g.Count(),
g.Key.Year,
g.Key.Month
};
db.tblForumAuthors
.GroupBy(c => new {c.Join_date.Month, c.Join_date.Year})
.OrderBy(g => g.Key.Year).ThenBy(g => g.Key.Month)
.Select(g => new
{
Registrations = g.Count(),
Year = g.Key.Year
Month = g.Key.Month
});
I'll bet there are better ways to do it, but here's one.
If the table had two fields defined like this:
tblForumAuthor
==========================
Join_Date date
Name nvarchar(50)
You could get a report of the number of people joining in each Month+Year combo like this:
var db = new DataClasses1DataContext();
var report =
from a in db.tblForumAuthors
group a by new {Year = a.Join_Date.Year, Month = a.Join_Date.Month}
into g
select new
{
Year = g.Key.Year,
Month = g.Key.Month,
Registrations = g.Count()
};
foreach( var item in report)
{
Console.WriteLine(item.Year + " " + item.Month + " " + item.Registrations);
}
it is more like this - sorry don't have ability to test it
var results = from r in tblForumAuthorm
group r by r.Join_date into
select new { Year =r.Join_Date.Year, Month = r.join_date.month };
How can i convert this in LINQ?
SELECT B.SENDER, B.SENDNUMBER, B.SMSTIME, B.SMSTEXT
FROM MESSAGES B
WHERE EXISTS ( SELECT A.SENDER
FROM MESSAGES A
WHERE A.SENDER = B.SENDER
GROUP BY A.SENDER
HAVING B.SMSTIME = MAX( A.SMSTIME))
GROUP BY B.SENDER, B.SENDNUMBER, B.SMSTIME, B.SMSTEXT ;
Thanks a lot :)
EDIT!!
Resolved with:
var Condition = "order by SMSTime desc";
IEnumerable<ClassMessaggio> messaggi = Database.Select<ClassMessaggio>(Condition);; // Load all but sorted
ElencoConversazioni = messaggi.GroupBy(m => new { m.Number })
.Select(g => g.OrderByDescending(m => m.SMSTime).First()).ToObservableCollection();
Try
db.Messages.Where(b => b.SmsTime == Messages.Where(a => a.Sender == b.Sender)
.Max(a => a.SmsTime))
Or
db.Messsages.GroupBy(m => new { m.Sender, m.SendNumber })
.Select(g => g.OrderByDescending(m => m.SmsTime).First())
Where db is your DataContext.
To show the list of conversations along with "the last message of every contact", you could try something like:
// a query to find the last Sms time per sender
var lastSmsQuery = from m in db.messages
group m by m.Sender into grouping
select new
{
Sender = grouping.Key,
LastSmsTime = grouping.Max(x => x.SmsTime)
};
// a query to find the messages linked to the last Sms per sender
var lastMessageQuery = from m in db.messages
join l in lastSmsQuery on new { m.Sender, m.SmsTime } equals new { l.Sender, l.LastSmsTime }
select m;
The 2-query method used is similar to that of this question from earlier today - Convert SQL Sub Query to In to Linq Lambda