Link to this two topics:
Convert Lambda Expression of a query to linq version
and
return items that all records related to that items have specific conditions
in first topic @xanatos comment that :
@Kerezo Be aware that the new { r.City } error appears twice (once in each query). new { r.City } creates an anonymous object with a single property called City that contains the City object (so you are wrapping your City in an object) Without the new you have directly the City
consider this code:
var citiesToExclude = from r in ent.TestAllStatusEqualsOnes
where r.Status != 1
select r.City;
GridView1.DataSource = citiesToExclude;
GridView1.DataBind();
if I wrote this code in this way:
var citiesToExclude = from r in ent.TestAllStatusEqualsOnes
where r.Status != 1
select new { r.City };
GridView1.DataSource = citiesToExclude;
GridView1.DataBind();
every thing are equal.
I don’t understand what is the differencr between select r.Field and select new {r.Field}. can any one explain more?
thanks
Anonymous types are pretty much the same as any other type. So:
is pretty much identical to:
with:
This then, perhaps makes the distinction simple; it is same as the difference between:
and
In one case, what you are obtaining is the city name. In the other case, you are obtaining an object that has a property called
Citywhich is the city name (although it could, in the general case, have other properties too).The same logic applies inside LINQ.
One handy difference between the two is considering
null, for example:if you are selecting the actual city name, it is a bit hard to tell the difference between “no row” vs “a row, with a null city name”. If you are selecting an object, you can tell between
obj == nullvsobj.City == null.