0

On some code I have right now we are executing our LINQ to SQL queries like so:

db.Customers.Where(c => c.Name.StartsWith("A"))
.OrderBy(c => c.Name).Select(c => c.Name.ToUpper());

But a lot of examples I see, the Linq to SQL code is written like:

var query =
   from c in db.Customers
   where c.Name.StartsWith ("A")
   orderby c.Name
   select c.Name.ToUpper();

I am worried that we are fetching the whole table in the current code, and afterwards manipulating it locally, which from my point of view is not efficient compared to having the SQL server doing it.

Is the two examples equivalent or is there a difference?

Hylle
  • 1,087
  • 1
  • 14
  • 25

2 Answers2

1

After finding out that what I was searching for was called "linq vs. method chaining", I found my answer here:

.NET LINQ query syntax vs method chain

The question is whether there's a difference between method chaining and linq query, as I have described in my question.

The answer is that there is none, you are free to use both methods. Comments mention there might be minor differences in the compilation time, but this is not my concern.

Hylle
  • 1,087
  • 1
  • 14
  • 25
0

This might be superfluous information, but in both code blocks you are not going to get anything from the database. At this point, you will only have told LINQ what query it should run. To actually run the query you're going to need to add a call to .First, .FirstOrDefault, .Single, .SingleOrDefault, .ToList, or their async counterparts.

Sangman
  • 171
  • 10