I have some code that changes a value of some data within my database while within a loop. I’m just wondering what is the most efficient way of filtering my data first? I’ll give an example:-
With the class:-
public class myObj
{
int id {get;set;}
string product {get; set;}
string parent{get;set;}
bool received {get;set;}
}
And the DbContext:-
public class myCont:DbContext
{
public DbSet<myObj> myObjs {get;set;}
}
Is it better to do this:-
int[] list;
/* Populate list with a bunch of id numbers found in myOBjs */
myCont data = new myCont();
myObj ob = data.myObjs.Where(o => o.parent == "number1");
foreach(int i in list)
{
ob.First(o => o.id == i && o.received != true).received = true;
}
Or:-
int[] list;
/* Populate list with a bunch of id numbers found in myOBjs */
myCont data = new myCont();
foreach(int i in list)
{
data.myObjs.First(o => o.parent == "number1" && o.id == i && o.received != true).received = true;
}
Or is there no difference?
Not sure how you get to compile your code example above.
In your
myObjobject, thereceivedproperty is anint, yet you are evaluating it against aboolwhich should cause this lineo.received != trueto results in an errorCannot apply operator '!=' to operands of type 'int' and 'bool'.To Check the SQL
Once the code compiles use SQL Profiler to see what SQL is generated.
That will show you the constructed SQLs
Benchmarking
The below is a very crude description of only one possible way you can benchmark your code execution.
Wrap your code into a method, for example:
And:
Crate a method which iterates x amount of times over each method using the
Stopwatchsimilar to this:Evaluate the results similar to this: