- var londonCustomers = from c in Customers
-
where (c.City.Equals("London") && c.CreditCardType.Equals("Visa"))
-
select c;
If you only needed certain parts, then you'd use the select to filter the relevant fields. For example:
- from c in Customers
-
where customer.City.Equals("London")
-
select new { Name = c.Name, PostCode = c.PostCode }
You could also use method syntax instead of query syntax:
- var londonCustomers = Customers.Where(c => c.City.Equals("London") && c.CreditCardType.Equals("Visa"));
Of course, you'd need to understand lambda expressions to be able to do that.
You could also do this without LINQ:
- var londonCustomers.Find(c => c.City.Equals("London") && c.CreditCardType.Equals("Visa"));
The beauty of the non-LINQ syntax is that it works in .NET 2.0 codebases
When you're thinking about LINQ, it does have some similarities to SQL, but it's not the same. You need to think about it slightly differently. Sure you've got your "from c in Customers", but your "where" isn't structured the same way as in SQL:
The where clause is basically the same as your .NET 2.0 find. Your query is iterating every object in your collection, so you treat each object exactly as you would if you were writing code relating to it - think of an if statement:
- if (c.Location.Equals("London") && (c.PostCode.StartsWith("EC1") || c.PostCode.StartsWith("SW11")) { ... }
Your where clause is exactly the same...