\$\begingroup\$
\$\endgroup\$
7
This is my code:
var test = (from x in myDb.myTable
where (x.name == tmp || x.name == tmp2 || x.name == tmp3) && x.unit == u
select x).FirstOrDefault();
if (test == null)
test = (from x in myDb.myTable
where (x.name == tmp || x.name == tmp2 || x.name == tmp3)
select x).FirstOrDefault();
How to optimize it>?
Olivier Jacot-Descombes
5,75822 silver badges27 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
4
var test = (from x in myDb.myTable
where (x.name == tmp || x.name == tmp2 || x.name == tmp3)
select x)
.AsEnumerable()
.OrderBy(x => x.unit == u ? 0 : 1)
.FirstOrDefault();
I removed the x.unit == u
condition. Instead I sort the items to make the ones where
this condition would be met to appear first. FirstOrDefault
then makes the rest.
I split the EF part from the LINQ-to-objects part with AsEnumerable()
as I am not sure if EF can translate the order by to SQL. If it can, you can try this
var test = (from x in myDb.myTable
where (x.name == tmp || x.name == tmp2 || x.name == tmp3)
orderby x.unit == u ? 0 : 1
select x)
.FirstOrDefault();
svick
24.5k4 gold badges53 silver badges89 bronze badges
answered Jan 21, 2013 at 15:25
-
\$\begingroup\$ Tnx for your answer. But will you pls explain how will this fasten the execution? \$\endgroup\$Srcee– Srcee2013年01月21日 18:43:56 +00:00Commented Jan 21, 2013 at 18:43
-
\$\begingroup\$ @Srcee It will always make a single query, while your code might make two queries. Making smaller number of queries is usually more efficient. \$\endgroup\$svick– svick2013年01月21日 18:52:32 +00:00Commented Jan 21, 2013 at 18:52
-
\$\begingroup\$ @Srcee: You did not specify what you wanted to have optimized (execution speed, code size, code maintainablity, others?). My solution will be faster, because it queries the database only once in any case. \$\endgroup\$Olivier Jacot-Descombes– Olivier Jacot-Descombes2013年01月21日 21:45:49 +00:00Commented Jan 21, 2013 at 21:45
-
\$\begingroup\$ I wanted to fasten the time, so I guess your solution will work. \$\endgroup\$Srcee– Srcee2013年01月22日 07:21:51 +00:00Commented Jan 22, 2013 at 7:21
lang-cs
tmp
andtmp2
(which are bad variable names, BTW) as theirname
, why is it okay to get any one of them? What is the schema of your table? How many rows does your table have? Does it have any indexes? \$\endgroup\$