Paging using Linq [duplicate] - linq

This question already has answers here:
LINQ and pagination [duplicate]
(3 answers)
Closed 9 years ago.
I need to apply paging logic to this Query. How can i do that?
My query is as follows,
myresultset = from req in myreqTable
join streq in myStreqTable on req.ID.ToString() equals new SPFieldLookupValue( Convert.ToString( streq[FormID] ) ).LookupValue
where (filter(req) && filter1(streq))
join plnts in plantDetails on Convert.ToString( streq[RequestID) equals Convert.ToString(plnts[RequestID]) into mySet
from s in mySet.DefaultIfEmpty()
select new Mytable() {
FormID = Convert.ToString(streq[FormID]),
RequestID = Convert.ToString(streq[RequestID])
};

Add .Skip( pageSize * pageIndex ).Take( pageSize ); to the end of your query. Note that pageIndex is zero-based (so the first page is 0, the second page is 1 and so on).
However your Linq doesn't look valid to me, and has some syntax errors. Are you sure this is your code as it is in your editor?

recordsForCurrentPage = myresultset.Skip( recordsPerPage * pageNumber ).Take( recordsPerPage )
This is assuming that your page number starts with 0. Otherwise subtract 1 from pageNumber.

Use Take and Skip methods:
myresults = myresults.Skip((page - 1) * pageSize).Take(pageSize);
I assumed page numeration starts from 1.

Related

Auto Increment ID in SQL [duplicate]

This question already has answers here:
Auto Increment after delete in MySQL
(18 answers)
Closed 12 months ago.
I want to know how can I make my SQL Database table give an ID starting from 0 and with every new add to check if there is an old ID free .
Exemple :
I added 10 items then I deleted almost everyone and I kept item with ID=5.
After adding a new item , it gets id 11 not 0.
Note : I'm editing my DB with Laravel API.
SQL AUTO INCREMENT adds 1 to the biggest incrementable column value.
To fill a free integer slot you need to check for it manually, but that kinda defeats the purpose of auto-incrementing.
Anyway here is how to check for the first free ID value:
function getUnusedId($ids_array)
{
$max_id = max($used_ids); // can be 25 for example
// [1:(id|1), 2:(id|2), 3:(id|3), 4:(id|5)] =>> ID 4 is missing
for($i = 1; $i <= $max_id; $i++){
if($used_ids[$i] > $i){
return $i;
}
}
return $max_id + 1; // You can echo that all IDs are used.
}
// The IDs must be ordered for this solution
$used_ids = Model::orderBy('id')->pluck('id')->toArray();
$free_id = getUnusedId($used_ids);

How can I get a random record in LINQ to SQL when Guid doesnt work [duplicate]

This question already has answers here:
linq select a random row
(6 answers)
Closed 3 years ago.
I want to select 1 random record. I use LINQ to SQL for my query, but im not really familiar with these (I know normal SQL queries better)
This is my code:
public void giveRand()
{
var query = (from Performance in db.Performances.OrderBy(c => Guid.NewGuid()).Take(1)
join Stage in db.Stages on Performance.stage_id equals Stage.stage_id
join Artist in db.Artists on Performance.artist_id equals Artist.artist_id
select new AllClass(db)
{
all_performance_id = Performance.performance_id,
all_starttime = Performance.starttime,
all_endtime = Performance.endtime,
all_artistname = Artist.name,
all_stagename = Stage.name,
all_artistdesc = Artist.description,
all_stagedesc = Stage.description
}).Single();
App.Current.Properties["timestart"] = query.all_starttime;
App.Current.Properties["timeened"] = query.all_endtime;
App.Current.Properties["namea"] = query.all_artistname;
App.Current.Properties["names"] = query.all_stagename;
App.Current.Properties["desca"] = query.all_artistdesc;
App.Current.Properties["descs"] = query.all_stagedesc;
}
I dont know whats wrong.
I'd follow the advice from the comment and rewrite a bit the query.
But, to answer your question, you can use Skip(random)+Take(1):
Random r = new Random();
int n = // number of records
var record = ... /* linq query */ .Skip(r.Next(0, n)).Take(1)

Oracle Apex get Multiple results from checkboxes

DB = Oracle 11g
Apex = 4.2.6
In the form I have various items which all work great. However I now have a set of check boxes(:P14_DAYS) one for each day of the week.
What I need to do is get all records between :P14_START_DATE :P14_END_DATE, but only within the days select that's checked.
Below is also a sample of the DATE_SETS table
http://i.stack.imgur.com/YAckN.png
so for example
dates 01-AUG-14 - 5-AUG-14 But only require Sundays AND Mondays date would bring back 2 refs.
BEGIN
UPDATE MD_TS_DETAIL
SET job_for = :P14_JOBFORTEM,
job_type_id = :P14_JOB_TYPE_VALUE,
account_id = :P14_ACC_VAL,
qty = :P14_HRS,
rio = :P14_RIO,
post_code = :P14_POSTCODE
WHERE id IN (SELECT D.id
FROM MD_TS_MAST M
LEFT JOIN MD_TS_DETAIL D
ON M.mast_id = D.md_id
LEFT JOIN DATE_SETS
ON ms_date = dt
WHERE eng_id = :P14_ENG_VAL
AND ms_date BETWEEN :P14_START_DATE AND :P14_END_DATE
AND DATE_SETS.col_day = ANY instr(':'||:P14_DAYS||':',Return)
END;
Any help would be much appreciated .
I found this example: http://docs.oracle.com/cd/B31036_01/doc/appdev.22/b28839/check_box.htm#CHDBGDJH
As I can understand, when you choose some values in your checkbox list, item :P14_DAYS receives value, that contains return values of chosen elements of the LOV with delimiters. Then you need to replace this string in your query
AND DATE_SETS.col_day = ANY instr(':'||:P14_DAYS||':',Return)
with
AND instr(':'||:P14_DAYS||':', ':'||DATE_SETS.col_day||':') > 0
Here function instr searches substring DATE_SETS.col_day in string :P14_DAYS. It returns position of substring if substring was found or 0, if not found. Then you compare result of function with 0, and if result > 0, it means that DATE_SETS.col_day is among selected values.

Get index of object in a list using Linq [duplicate]

This question already has answers here:
How to get index using LINQ? [duplicate]
(7 answers)
Closed 8 years ago.
I am new to Linq. I have a Customers table.ID,FullName,Organization,Location being the columns. I have a query in Sqlite returning me 2500 records of customers. I have to find the index of the customer where ID=150 for example from this result set. Its a List of Customers. The result set of the query is ordered by organization. I tried with FindIndex and IndexOf but getting errors for the former and -1 for the latter. So, how should it be done?
Thanks.
You don't need to use LINQ, you can use FindIndex of List<T>:
int index = customers.FindIndex(c => c.ID == 150);
Linq to Objects has overloaded Select method
customers.Select((c,i) => new { Customer = c, Index = i })
.Where(x => x.Customer.ID == 150)
.Select(x => x.Index);
Keep in mind, that you should have in-memory List<Customer> to use this Linq to Objects method.

How to query and calculate dates in the where clause of a LINQ statement?

I am having trouble with the following piece of code. Before I paste it, Let me give a bit of history on what should happen.
I have a model containing 2 fields of interest at the moment, which is the name of the order the customer placed, and the date at which he/she placed it. A pre-calculated date will be used to query the dateplaced field (and should only query the dates , and not the time). The query counts the amount of duplicates that occur in the MondayOrder field, and groups them together. Now , when I exclude the where clause which should query the dates, the query runs great. However, The goal of this query is to count the amount of orders for the following week based on the date the order has been placed.
List<string> returnlist = new List<string>();
DateTime dt = getNextWeekMondaysDate().Date;
switch (day)
{
case DayOfWeek.Monday:
{
var CountOrders =
from x in Data.EntityDB.Orders
group x by x.MondayOrder into m
let count = m.Count()
select new
{
MondayOrderItem = m.Key, Amount = count
};
foreach (var item in CountOrders)
{
returnlist.Add(item.MondayOrderItem + " : " +
item.Amount);
}
}
break;
The getNextWeekMondaysDate() method has an overload which I can use, where if I supply it a date, it will get the following Monday's date from the parameter given. The problem is though, LINQ does not accept queries such as the following:
var CountOrders =
from x in Data.EntityDB.Orders
where getNextWeekMondaysDate(x.DatePlaced.Value).Date == dt
group x by x.MondayOrder into m
let count = m.Count()
select new { MondayOrderItem = m.Key, Amount = count };
This is exactly what I must achieve. Is there any workaround for this situation?
UPDATE
Here is the exception I get when I try the 2nd query.
LINQ to Entities does not recognize the method 'System.DateTime getNextWeekMondaysDate(System.DateTime)' method, and this method cannot be translated into a store expression.
You cannot do this directly, as user-defined method calls cannot be translated to SQL by the EF query provider. The provider recognizes a limited set of .NET methods that can be translated to SQL and also a number of canonical functions as well. Anything that cannot be expressed using these methods only is off-limits unless you write your own query provider (which is only theoretically an option).
As a practical workaround, you can calculate an appropriate range for x.DatePlaced.Value in code before the query and then use specific DateTime values on the where clause.
As an intellectual exercise, note that this method is recognized by the query provider and can be used as part of the expression. So this abomination should work too:
var CountOrders =
from x in Data.EntityDB.Orders
where EntityFunctions.AddDays(
x.DatePlaced.Date.Value,
(9 - DateAndTime.DatePart(DateInterval.WeekDay, x.DatePlaced.Value)) % 7)
.Date == dt
group x by x.MondayOrder into m
let count = m.Count()
select new { MondayOrderItem = m.Key, Amount = count };
Linq to Entities doesn't know how to convert arbitrary C# methods into SQL - it's not possible in general.
So, you have to work with the methods it does understand.
In this case, you could do something like this:
DateTime weekBegin = CalculateWeekBegin( dt );
DateTime weekEnd = CalculateWeekEnd( dt );
var CountOrders =
from x in Data.EntityDB.Orders
where x.DatePlaced.Value >= weekBegin && x.DatePlaced.Value < weekEnd
group x by x.MondayOrder into m
let count = m.Count()
select new { MondayOrderItem = m.Key, Amount = count });

Resources