I am trying to sort all the updated item in DataTableA, by coloring the item that has not been completely updated, and removing the item that has been updated completely from the DataTable. both The item that has been updated completely and the incomplete updated item are in "managed" table in the database, the discharge date will be null if it has not been completely updated.
Below code works but it can take all day for the page to run. This is C# webform.
The code below is writing on my code behind file:
foreach (GridDataItem dataItem in RadGrid1.Items)
{
var panu = dataItem["Inumber"];
var panum = panu.Text;
var _cas = db.managed.Any(b =>
b.panumber == panum && b.dischargedate != null);
var casm = db.managed.Any(b =>
b.panumber == panum && b.dischargedate == null);
if (_cas == true)
{
dataItem.Visible = false;
}
if (casm == true)
{
dataItem.BackColor = Color.Yellow;
}
}
As mentioned in the comment, each call to
db.managed.Anywill create a new SQL query.There are various improvements you can make to speed this up:
First, you don't need to call
db.managed.Anytwice inside the loop, if it's checking the same unique entity. Call it just once and checkdischargedate. This alone with speed up the loop 2x.If
panumberis not a unique primary key and you don't have a sql index for this column, then eachdb.managed.Anycall will scan all items in the table on each call. This can be easily solved by creating an index withpanumanddischargedate, so if you don't have this index, create it.Ideally, if the table is not huge, you can just load it all at once. But even if you have tens of millions of records, you can split the loop into several chunks, instead of repeating the same query over and over again.
Consider using better naming for your variables.
_casandcasmare a poor choice of variable names.So if you don't have hundreds of thousands of items, here is the simplest fix: load
panumberanddischargevalues for all rows from that table into memory, and then use a dictionary to instantly find the items:If the table is huge and you only want to load certain items, you would do:
But there is a limit on how large
someListcan be (you don't want to run this query for a list of 200 thousand items).