I am completely new to Linq and wondering if you can help me understand the difference between the following Linq? For example...
//normal select
var contacts = entity.Contacts.Select(n => n.FirstName);
//select new
var contacts2 = entity.Contacts.Select(n => new { n.FirstName });
//normal select output
foreach (var c in contacts)
Response.Write(c + "<br/>");
//select new output
foreach (var c in contacts2)
Response.Write(c.FirstName + "<br/>");
The only difference I can see is that in the normal select, the firstname (string) is stored in the collection, whereas in the select new, a contact object is stored in the collecton and the firstname being accessed by its property. Also the select new returns the properties only selected in the statement.
Another difference I noticed is that you can return multiple specific properties in the select new.
In what scenario would you choose one over the other?
Thanks for the help.
Select and SelectMany are projection operators. A select operator is used to select value from a collection and SelectMany operator is used to selecting values from a collection of collection i.e. nested collection.
The major difference between First() and FirstOrDefault() is First will throw an exception when there are no results and FirstOrDefault won't. In fact, FirstOrDefault will simply return the null value (reference types) or the default value of the value type.
In a query expression, the select clause specifies the type of values that will be produced when the query is executed. The result is based on the evaluation of all the previous clauses and on any expressions in the select clause itself. A query expression must terminate with either a select clause or a group clause.
@CYB: select new is used when you want your query to create new instances of a certain class, instead of simply taking source items. It allows you to create instances of a completely different class, or even an anonymous class like in OP's case.
n => n.FirstName
gives you a string
n => new { n.FirstName }
gives you an anonymous type, with one string
property called FirstName
In general, an anonymous type with just one property is probably not what you're looking for, so I'd go for the first option.
To support Richard Ev's answer:
If you are not familiar with Anonymous types, crack up ildasm and give your exe as an input to it.
You will get something like this:
The thing that you see starting with <>f_AnonymousType() is the one that Richard Ev is talking about. Your syntax of new
got translated into a new class (the name was decided by compiler). That is why var
keyword is so helpful working with anonymous type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With