tags:

views:

73

answers:

3

Can I improve this LINQ query

var filter = from Dep in deptlist
where (Dep.DepNm.StartsWith(txt1.Text.ToLower()) 
  || Dep.DepNm.StartsWith(txt1.Text.ToUpper())
  ||Dep.DepNm.Contains(txt1.Text)) 
select Dep;
+1  A: 
var filter = from Dep in deptlist
where Dep.where(d => d.DepNm.ToUpper().Conatins(txt1.Text.ToUpper())) 
select Dep;

If it's possible in your solution, add lambda expressions. So you saved at least one line :)


EDIT: Forget what I was saying, this is MUCH shorter:

var filter = deptlist.where(d => d.DepNm.ToUpper().Conatins(txt1.Text.ToUpper())).ToList();
yan.kun
I don't think your answer does the same as the LINQ in the OP's question
Matt Ellen
A: 

I think it's faster because there is less conditions.

var filter = from Dep in deptlist
where (Dep.DepNm.StartsWith(txt1.Text, StringComparison.OrdinalIgnoreCase))
||Dep.where(d => d.DepNm.ToUpper().Contains(txt1.Text.ToUpper()))
select Dep;
Florian
+3  A: 

Currently, you do a .Text, .Text.ToUpper() and .Text.ToLower() of the fixed value per item; (the ToUpper() etc being relatively expensive); you can lift this out:

string text = txt1.Text, upper = text.ToUpper(), lower = text.ToLower();
var filter = from Dep in deptlist
             where Dep.DepNm.StartsWith(lower) || Dep.DepNm.StartsWith(upper)
                   || Dep.DepNm.Contains(text)) 
             select Dep;

I'm assuming here that .DepNm is trivially cheap. If this is actually an expensive property to query, you can use let to minimise the calls:

var filter = from Dep in deptlist
             let name = Dep.DepNm
             where name.StartsWith(lower) || name.StartsWith(upper)
                   || name.Contains(text)) 
             select Dep;
Marc Gravell