views:

118

answers:

3

Just began to develop using LINQ, and still can't understand some simple things. So, LinqTable.SingleOrDefault(t=>(t.Field1=="value1")) is equal to SQL "SELECT * FROM LinqTable WHERE Field1="value1" LIMIT 1"

How to create (using Linq) the query like "SELECT * FROM LinqTable WHERE Field1="value1" AND Field2="value2" LIMIT 1?

+1  A: 

SingleOrDefault(t=>(t.Field1=="value1" && t.Field2=="value2"))

brian
I tried it before and It didn't work, I swear! But now I tried again and it works.Thank you
setrul
+1, you don't have to use the extra (). @Setrul: to understand LINQ better, do a Google search for "LINQ 101"
Zyphrax
+1  A: 

Normally, you'd want to use Where to do this:

var result = LinqTable.Where(t => t.Field1 == "value1" && t.Field2 == "value2").SingleOrDefault();

You can do this directly in the SingleOrDefault line as well:

var result = LinqTable.SingleOrDefault(t => t.Field1 == "value1" && t.Field2 == "value2");
Reed Copsey
Don't use Where but use the overload of SingleOrDefault that accepts a predicate.
Zyphrax
Both options work, fine, and actually will create the same SQL in EF and L2S. Personally, I find using Where more descriptive, in this instance, given the goals of the OP.
Reed Copsey
+1  A: 
LinqTable.Where(row => row.Field1 == "value1" && row.Field2 == "value2").FirstOrDefault();
Jay
+1 for FirstOrDefault(). The question, as stated, doesn't indicate that the values would find a unique result.
p.campbell