How to select from a table by date using linqq - sql

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();

Related

mvc5 create new select from query

this is the query :
var data = db.tableone.Where(a => a.type == 1).Select(u => new {id = u.id, type = u.type,newcolumnnotexistindatabase = "test"} );
return data.ToList();
while there is 5 column by the type of 1, it should show me in list
id, type -- newcolumnnotexistindatabase
1 , 1 --test
2 , 1 --test
3 , 1 --test
4 , 1 --test
5 , 1 --test
ERORR:
can not implicitly convert type 'System.Collections.Generic.List<<
The problem is that, you can't return anonymous type. If return type of your function is List<<AnyClass>> , your linq query should be like this:
var data = db.tableone
.Where(a => a.type == 1)
.Select(u => new AnyClass
{
id = u.id,
type = u.type,
newcolumnnotexistindatabase = "test"
} );
return data.ToList();

Translating SQL results to LINq with join of literal

All,
This is my first post to this forum and I have searched all throughout this site to find an answer to my question, but it looks like there is not an example of what I need to do.
Below is a SQL query I need to adapt to a LINQ statement:
select COUNT(pe2.*)
from SomeTable pe1
inner join SomeTable pe2 on (pe2.Id=pe1.Id and pe2.TypeCode='X')
where pe1.TypeCode='Y'
I have tried to join this as illustrated below, but it doesn't work:
var query = (from pe2 in SomeTable
join pe1 in SomeTable
on new { pe1.Id } equals new {pe2.Id }
where pe2.TypeCode == "X"
&& pe1.TypeCode == "Y"
select pe2).Count();
Since the TypeCode is HardCoded you can pass it to the where clause
select pe2.*
from SomeTable pe1
inner join SomeTable pe2 on pe2.Id=pe1.Id
where pe1.TypeCode='Y'
and pe2.TypeCode='X'
And here it's how I would do it in linq
var l1 = new List<dynamic> { new { Id = 1, Code = "X" }, new { Id = 2, Code = "Y" } };
var l2 = new List<dynamic> { new { Id = 1, Code = "Y" }, new { Id = 2, Code = "X" } };
//lambda expression
l1.Join(l2,
x => x.Id,
y => y.Id,
(x, y) => new { Pe1 = x, Pe2 = y })
.Where(x => x.Pe1.Code == "Y" && x.Pe2.Code == "X")
.Select(x => x.Pe2);
//query...
from x in l1
join y in l2 on x.Id equals y.Id
where x.Code == "Y"
&& y.Code == "X"
select y
from x in l1
from y in l2
where x.Id == y.Id
&& x.Code == "Y"
&& y.Code == "X"
select y

Get Rank from from Total LINQ Query

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
};

sqlLinq Take higher RN number

Here is My Query
var sonuc = (from c in cd.Product
join pp in cd.Product_Picture_Mapping
on c.ID equals pp.ProductID
join pcc in cd.Picture
on pp.PictureID equals pcc.ID
select new ProductViewModel() { PicturePath = pcc.Path, ProductID = c.ID }).OrderBy(x => x.ProductID).ToList().AsEnumerable().Select((entry, index) => new ProductViewModel()
{
PicturePath = entry.PicturePath,
ProductID = entry.ProductID
}).OrderBy(x => x.ProductID).GroupBy(x => x.ProductID).Select(g => new { g, count = g.Count() })
.SelectMany(t => t.g.Select(b => b).Zip(Enumerable.Range(1, t.count), (j, i) => new { j.ProductID, j.PicturePath, rn = i }));
and OUTPUT;
PicturePath ProductID RN
samplepath1 4 1
samplepath2 5 1
samplepath3 10 1
samplepath4 10 2
samplepath5 10 3
so, i want to take one row that have same Product id by higher RN, like this.
PicturePath ProductID RN
samplepath1 4 1
samplepath2 5 1
samplepath5 10 3
How can i get like this ?
Thank you
Group by ProductID and select item with max RN from each group:
var result = from x in sonuc
group x by x.ProductID into g
select g.OrderByDescending(x => x.RN).First();

Trouble converting simple SQL to Linq

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 };