pagination in C# console application [duplicate] - c#

var q = (from Comments in db.tblBlogComments where Comments.blogID == this.ID orderby Comments.date descending select new {
Comments.userID, Comments.comment, Comments.date
});
This returns ALL my associated records, how best would I select say records #10 to #20 only so I don't load any redundant data?

How about:
var q = (
from Comments in db.tblBlogComments
where Comments.blogID == this.ID
orderby Comments.date descending
select new { Comments.userID, Comments.comment, Comments.date }).Skip(10).Take(10);

You can use the .Skip() and .Take() methods on your result set. Example:
var q = (from Comments in db.tblBlogComments where Comments.blogID == this.ID orderby Comments.date descending select new {
Comments.userID, Comments.comment, Comments.date
});
And then use:
int pageSize = 10;
int page = 3;
var currentPage = q.Skip((currentPage - 1) * pageSize).Take(pageSize);
And then
foreach(var item in currentPage)
{
...
}
Since Linq uses deferred execution, the actual query will be created and executed during the foreach loop. So the SQL query will only return the records for the current page.
Edit: More information about this subject

int start = 10;
int end = 20;
var q = (from Comments in db.tblBlogComments
where Comments.blogID == this.ID
orderby Comments.date descending
select new {
Comments.userID,
Comments.comment,
Comments.date
}).Skip(start).Take(end - start);
I'm not sure if Skip translates to SQL executed in the database, so this might be not so efficient.

Related

LINQ Query to Filter then to a Model

How can I do this correctly?
This is failing because schedule-on does not exist within m from RR2.
var RR = (from m in DataContext.csrcallds
where m.scheduledon >= earliestDate
&& m.scheduledon <= objdate1.DateStart
&& m.assignto == 113
&& (SqlMethods.DateDiffDay(m.scheduledon, m.completedon) > 5)
select m
);
var RR2 = RR.Select(x => (GetBusinessDays((DateTime)x.scheduledon, (DateTime)x.completedon)) > 5).ToList());
var RnR = (from m in RR2
group m by new { m.scheduledon.Value.Year, m.scheduledon.Value.Month } into p
orderby p.Key.Year ascending, p.Key.Month ascending
select new Date1()
{
theDate = DateTime.Parse($"{p.Key.Month} - {p.Key.Year}"),
theCount = p.Count(),
theString = $"{p.Key.Month} - {p.Key.Year}"
});
I am trying to query all the results.
Then use my GetBusinessDay function to filter out the ones I don't need, gathering only the records within 5 business days.
Then put the results into my Model named Date1.
I'm trying to do it like this because I cannot use GetBusinessDays within an LINQ query.
So I'm trying to filter it outside of SQL, then group the records again.
How do I go about accomplishing this task?
You could add this to your SQL Query to filter out the weekend days.
SELECT *
FROM your_table
WHERE ((DATEPART(dw, date_created) + ##DATEFIRST) % 7) NOT IN (0, 1)
Or This
select [date_created]
from table
where DATENAME(WEEKDAY, [date_created]) <> 'Saturday'
and DATENAME(WEEKDAY, [date_created]) <> 'Sunday'
Or if you have to stick to LINQ try the ideas outlined here:
Linq query DateTime.Date.DayOfWeek
DateTime firstSunday = new DateTime(1753, 1, 7);
var bookings = from b in this.db.Bookings
where EntityFunctions.DiffDays(firstSunday, b.StartDateTime) % 7 == 1
select b;
Solved by using function workdays server side:
https://stackoverflow.com/a/252532/6157660
Allows me to make a simple LINQ query, and gives me what I need.
I did edit the function to remove the +1 from DateDiff. as same days should be 0 not 1.
Thank you guys for your help!
var RnR = (from m in DataContext.csrcallds
where m.scheduledon >= earliestDate
&& m.scheduledon <= objdate1.DateStart
&& m.assignto == 113
&& (DataContext.fn_WorkDays((DateTime)m.scheduledon, (DateTime)m.completedon)) > 5
group m by new { m.scheduledon.Value.Year, m.scheduledon.Value.Month } into p
orderby p.Key.Year ascending, p.Key.Month ascending
select new Date1()
{
theDate = DateTime.Parse($"{p.Key.Month} - {p.Key.Year}"),
theCount = p.Count(),
theString = $"{p.Key.Month} - {p.Key.Year}"
});

Entity framework average , group by query

Hello i have the following query
var myList = (from p in db.Full
where (p.date_reception > begin & p.date_reception < end & !p.mc_object.Contains("NULL")
& (!strListe.Contains(p.mc_object)))
group p by new { p.mc_object} into g
select g.OrderByDescending(p => new {p.duration,p.mc_object} ) into r
select new StringIntType
{
str = r.mc_object,
nbr = r.duration.Value
}).Take(50).ToList();
I need to group by mc_object , and select mc_object , average of duration
and order by average of duration descending ,Thank you for helping
The query should be
var myList = (from p in db.Full
// Don't use &! Use &&
where p.date_reception > begin &&
p.date_reception < end &&
!p.mc_object.Contains("NULL") &&
!strListe.Contains(p.mc_object)
group p by p.mc_object into g
select new
{
mc_object = g.Key,
/* data = g, */
avg = g.Average(x => x.duration)
} into h
// if you want both descending, add descending after mc_object
orderby h.avg descending, h.mc_object
select new StringIntType
{
str = h.mc_object,
nbr = (int)h.avg // Average returns a double
}).Take(50).ToList();
}
Note that I've changed the & to &&. For the ordering I wasnt sure. I dont need the full data in the second half of the query, so I've added a commented data = g

How to optimize linq query?

I have difficulty in getting an average score of students in each department.
while every department there are many faculties, each faculty there are many courses, each course there are many students, and every student has a lot of value.
the query that I have made, I get quite a lot of the time constraints that are required to display the same data capture.
please help to optimize the query that I made this.
double TotalNilaiMutu = 0;
double JumSKS = 0;
double ipkMhs = 0;
double totalIPK = 0;
var queryDepartemen = (from so in StrukturOrganisasis
join dp in Departemens on so.ID equals dp.ID
orderby dp.ID
select new{dp.ID, so.Inisial, so.Nama}).ToList();
foreach(var departemen in queryDepartemen){
var queryMayor = (from my in Mayors
where my.DepartemenID == departemen.ID && my.StrataID == 2
select my.ID).ToList();
var queryMhs = (from ms in MahasiswaSarjanas
where queryMayor.Contains(ms.MayorID) &&
(
from sm in StatusMahasiswas
where
(
from ts in TahunSemesters
where ts.TahunAwal == 2013
select ts.ID
)
.Contains(sm.TahunSemesterID)
select sm.NIM
)
.Contains(ms.NIM)
select ms.NIM).ToList();
ipkMhs = 0;
foreach(var nim in queryMhs){
var queryNilai = (from kr in KRS
join hm in HurufMutus on kr.HurufMutuID equals hm.ID
join kur in
(
from ku in Kurikulums
join mk in MataKuliahs on ku.MataKuliahID equals mk.ID
select new {ku.ID, mk.Nama, mk.SKS}
)
on kr.KurikulumID equals kur.ID
where kr.NIM==nim
select new {
nilai = hm.NilaiMutu * kur.SKS,
sks = kur.SKS
});
TotalNilaiMutu = 0;
JumSKS = 0;
foreach(var ipk in queryNilai){
TotalNilaiMutu += ipk.nilai;
JumSKS += ipk.sks;
}
if(double.IsNaN(TotalNilaiMutu/JumSKS)) ipkMhs+=0;
else ipkMhs += TotalNilaiMutu/JumSKS;
}
if(double.IsNaN(ipkMhs/queryMhs.Count())) totalIPK=0;
else totalIPK=ipkMhs/queryMhs.Count();
Console.WriteLine(departemen.Nama +" -> "+ totalIPK +" : "+ ipkMhs +" / "+queryMhs.Count());
}
Have you tried adding AsParallel()?
var queryDepartemen = (from so in StrukturOrganisasis.AsParallel()
join dp in Departemens on so.ID equals dp.ID
orderby dp.ID
select new{dp.ID, so.Inisial, so.Nama}).ToList();
foreach(var departemen in queryDepartemen.AsParallel()){
var queryMayor = (from my in Mayors
where my.DepartemenID == departemen.ID && my.StrataID == 2
select my.ID).ToList();
var queryMhs = (from ms in MahasiswaSarjanas.AsParallel()
where queryMayor.Contains(ms.MayorID) &&
(
from sm in StatusMahasiswas
where
(
from ts in TahunSemesters
where ts.TahunAwal == 2013
select ts.ID
)
.Contains(sm.TahunSemesterID)
select sm.NIM
)
.Contains(ms.NIM)
select ms.NIM).ToList();

no supported translation to sql error?

I am using linq to sql. I am running a query which uses a function to return the right record. I am using a function so I can use if statement which I dont know how to do it within the linq clause. The code is copied below. It returns an error: "GetPageOwner(int 32) has no supported translation to sql" what am i doing wrong? How to fix it to get the same results?
return (from page select new Result
{
pageOwner = GetPageOwner(page.page_id)
});
public Post GetPageOwner(int pageid)
{
var posts = (from dp in db.Posts where dp.pageid == pageid select dp);
var returned = posts;
if (posts.Count() > 0)
{
var latest = posts.OrderByDescending(o => o.Date).FirstOrDefault();
var sharedsamedayaslatest = (from p in posts where p.Date.AddDays(1) >= latest.Date select p);
if (sharedsamedayaslatest.Count() > 1)
{
var followedpost = (from p in posts from s in db.Subscriptions where s.Subscriber == UID && s.Subscribedto == p.UserId select p);
var count = followedpost.Count();
if (count == 1)
{
returned = followedpost;
}
else if (count > 1)
{
returned = (from s in followedpost let reposts = GetPostReposts(s.id) let rating = GetPostRating(s.id) let score = reposts + rating orderby score descending select s);
}
else
{
//no follower shared this post so return the most liked
returned = (from s in sharedsamedayaslatest let reposts = GetPostReposts(s.id) let rating = GetPostRating(s.id) let score = reposts + rating orderby score descending select s);
}
}
else
{
//no shares on the day the latest share
returned = sharedsamedayaslatest;
}
}
else
{
//only one post
returned = posts;
}
return returned.FirstOrDefault(); //order by userid gets a random one
}
Linq to sql has to translate functions from .net into sql. Not all .net functions have an equivalent in sql, and ones written by you definitely don't have one.
That being said you can implement your function as a stored procedure and use it in your linq query.

Linq Sub-Select

How do I write a sub-select in LINQ.
If I have a list of customers and a list of orders I want all the customers that have no orders.
This is my pseudo code attempt:
var res = from c in customers
where c.CustomerID ! in (from o in orders select o.CustomerID)
select c
How about:
var res = from c in customers
where !orders.Select(o => o.CustomerID).Contains(c.CustomerID)
select c;
Another option is to use:
var res = from c in customers
join o in orders
on c.CustomerID equals o.customerID
into customerOrders
where customerOrders.Count() == 0
select c;
Are you using LINQ to SQL or something else, btw? Different flavours may have different "best" ways of doing it
If this is database-backed, try using navigation properties (if you have them defined):
var res = from c in customers
where !c.Orders.Any()
select c;
On Northwind, this generates the TSQL:
SELECT /* columns snipped */
FROM [dbo].[Customers] AS [t0]
WHERE NOT (EXISTS(
SELECT NULL AS [EMPTY]
FROM [dbo].[Orders] AS [t1]
WHERE [t1].[CustomerID] = [t0].[CustomerID]
))
Which does the job quite well.
var result = (from planinfo in db.mst_pointplan_info
join entityType in db.mst_entity_type
on planinfo.entityId equals entityType.id
where planinfo.entityId == entityId
&& planinfo.is_deleted != true
&& planinfo.system_id == systemId
&& entityType.enity_enum_id == entityId
group planinfo by planinfo.package_id into gplan
select new PackagePointRangeConfigurationResult
{
Result = (from planinfo in gplan
select new PackagePointRangeResult
{
PackageId = planinfo.package_id,
PointPlanInfo = (from pointPlanInfo in gplan
select new PointPlanInfo
{
StartRange = planinfo.start_range,
EndRange = planinfo.end_range,
IsDiscountAndChargeInPer = planinfo.is_discount_and_charge_in_per,
Discount = planinfo.discount,
ServiceCharge = planinfo.servicecharge,
AtonMerchantShare = planinfo.aton_merchant_share,
CommunityShare = planinfo.community_share
}).ToList()
}).ToList()
}).FirstOrDefault();
var res = (from c in orders where c.CustomerID == null
select c.Customers).ToList();
or Make Except()

Categories

Resources