473,238 Members | 1,625 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,238 software developers and data experts.

Newbie LINQ Question

Hi, I have the following code extract...
---top---

List<PersonPersons = new List<Person>();
Persons.Add(new Person("Peter", 28,"Perth"));
Persons.Add(new Person("Matthew", 31, "Bundaberg"));
Persons.Add(new Person("Cathryn", 36, "Perth"));
//This works
IEnumerable<Personp1 = from op in Persons
where op.City=="Perth"
select op;

//Tut this doesn't work
List<Personp2 = from op in Persons
where op.City == "Perth"
select op;
---bottom---
The compiler error message is: Compiler Error Message: CS0266: Cannot
implicitly convert type
'System.Collections.Generic.IEnumerable<ASP.linq_l inqgrouping_aspx.Person>'
to
'System.Collections.Generic.List<ASP.linq_linqgrou ping_aspx.Person>'.
An explicit conversion exists (are you missing a cast?)

I'm trying to not get into the habit of using var because I read
somewhere (MSDN) that it makes your code more unreadable to others,
which I tend to agree with.

Can someone please tell me what I'm doing wrong?

Thanks in advance,
Damien
Jun 27 '08 #1
10 1184
On Jun 20, 8:51*am, "damiensaw...@yahoo.com.au"
<damiensaw...@yahoo.com.auwrote:

<snip>
I'm trying to not get into the habit of using var because I read
somewhere (MSDN) that it makes your code more unreadable to others,
which I tend to agree with.
I personally find that var *increases* readability rather than
reducing it, but it's a personal thing.
Can someone please tell me what I'm doing wrong?
Exactly what the compiler says - the result of the expression on the
RHS is IEnumerable<Person>, not List<Person>.
If you want it in a List, you should call ToList on the result of the
query expression.

Mind you, if you're *just* using a "where" clause the code would
probably be simpler as:
List<Personp2 = people.Where(person =>
person.City=="Perth").ToList();

(Note that I've changed "Persons" to "people" to follow naming
conventions and make for more comfortable reading :)

Jon
Jun 27 '08 #2
da**********@yahoo.com.au wrote:
Hi, I have the following code extract...
---top---

List<PersonPersons = new List<Person>();
Persons.Add(new Person("Peter", 28,"Perth"));
Persons.Add(new Person("Matthew", 31, "Bundaberg"));
Persons.Add(new Person("Cathryn", 36, "Perth"));
//This works
IEnumerable<Personp1 = from op in Persons
where op.City=="Perth"
select op;

//Tut this doesn't work
List<Personp2 = from op in Persons
where op.City == "Perth"
select op;
---bottom---
The compiler error message is: Compiler Error Message: CS0266: Cannot
implicitly convert type
'System.Collections.Generic.IEnumerable<ASP.linq_l inqgrouping_aspx.Person>'
to
'System.Collections.Generic.List<ASP.linq_linqgrou ping_aspx.Person>'.
An explicit conversion exists (are you missing a cast?)

I'm trying to not get into the habit of using var because I read
somewhere (MSDN) that it makes your code more unreadable to others,
which I tend to agree with.

Can someone please tell me what I'm doing wrong?
the 'from op in Persons where op.City == "Perth" select op;' part isn't
a List<Personbut an IEnumerable. If you want to have a List<Person>,
you should do:

List<Personp2 = (from op in Persons
where op.City == "Perth"
select op).ToList();

The background is that linq to objects, which is what you're using as
'Persons' is an IEnumerable and not an IQueryable containing a Linq
provider, simply does a foreach with a yield over your persons.

so the query is equal to this code:

foreach(Person op in Persons)
[
if(op.City!="Perth")
{
continue;
}
yield return op;
}

which simply produces an IEnumerable<PersonEnumerator, created by the
compiler.

FB

--
------------------------------------------------------------------------
Lead developer of LLBLGen Pro, the productive O/R mapper for .NET
LLBLGen Pro website: http://www.llblgen.com
My .NET blog: http://weblogs.asp.net/fbouma
Microsoft MVP (C#)
------------------------------------------------------------------------
Jun 27 '08 #3
Jon Skeet [C# MVP] wrote:
I personally find that var increases readability rather than
reducing it, but it's a personal thing.
You are in pretty good company on that score...

http://www.codinghorror.com/blog/archives/001136.html

Regards Tim.
--

Jun 27 '08 #4
Tim Jarvis wrote:
Jon Skeet [C# MVP] wrote:
>I personally find that var increases readability rather than
reducing it, but it's a personal thing.

You are in pretty good company on that score...

http://www.codinghorror.com/blog/archives/001136.html
'var' is only useful if you really don't know the type. In other
situations, it relies on the IDE to know the type:

var foo = SomeMethod();

vs.

int foo = SomeMethod();

Which one do you prefer? Readability of code is about being able to
understand immediately what's the intention of the code you're reading,
what it does. Knowing what type a variable has is essential. If I have
to mouse over a variable to understand what it is, it takes time plus I
have to rely on the IDE to be able to read the code. If I post the code
on a webpage there's no IDE to help me, also in other areas where IDE
help isn't there, the code should be readable and easy to understand.
'var' doesn't help there.

It's of no surprise that a VB using developer like Atwood likes var, as
VB uses:
Dim foo As New Bar()

which specifies the type once, and C# requires to specify the type
twice: with declaration and at construction. However that doesn't mean
it's better. Better be redundant and see the information TWICE than be
lacking of info and assume the reader will understand. Because that last
thing is the number 1 reason why there are bugs in a lot of code: the
reader assumes things while reading the code but the assumption is
wrong. Simply because we're humans and not a CLR.

FB

--
------------------------------------------------------------------------
Lead developer of LLBLGen Pro, the productive O/R mapper for .NET
LLBLGen Pro website: http://www.llblgen.com
My .NET blog: http://weblogs.asp.net/fbouma
Microsoft MVP (C#)
------------------------------------------------------------------------
Jun 27 '08 #5
Frans Bouma [C# MVP] <pe******************@xs4all.nlwrote:
You are in pretty good company on that score...

http://www.codinghorror.com/blog/archives/001136.html

'var' is only useful if you really don't know the type. In other
situations, it relies on the IDE to know the type:

var foo = SomeMethod();

vs.

int foo = SomeMethod();

Which one do you prefer?
Straw man, and easy to provide a counterexample for:

Dictionary<int,List<Person>peopleByAge =
new Dictionary<int,List<Person>>();

(Yes, I had to wrap onto two lines because it's so long...)

vs

var peopleByAge = new Dictionary<int,List<Person>>();

Which one do you prefer? What's the benefit of the redundancy here?

Sure, "var" isn't suitable for every situation - but there's a massive
difference between that and "it's only useful if you really don't know
the type". If the type is crystal clear from the RHS, I see no benefit
in repeating that information on the LHS.
It's of no surprise that a VB using developer like Atwood likes var, as
VB uses:
Dim foo As New Bar()

which specifies the type once, and C# requires to specify the type
twice: with declaration and at construction. However that doesn't mean
it's better. Better be redundant and see the information TWICE than be
lacking of info and assume the reader will understand.
In what way does my example lack any information? In what way is it not
obvious what the type of peopleByAge is?

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #6
Jon Skeet [C# MVP] wrote:
Frans Bouma [C# MVP] <pe******************@xs4all.nlwrote:
>>You are in pretty good company on that score...

http://www.codinghorror.com/blog/archives/001136.html
'var' is only useful if you really don't know the type. In other
situations, it relies on the IDE to know the type:

var foo = SomeMethod();

vs.

int foo = SomeMethod();

Which one do you prefer?

Straw man, and easy to provide a counterexample for:

Dictionary<int,List<Person>peopleByAge =
new Dictionary<int,List<Person>>();

(Yes, I had to wrap onto two lines because it's so long...)

vs

var peopleByAge = new Dictionary<int,List<Person>>();

Which one do you prefer? What's the benefit of the redundancy here?
I prefer the first one as we discussed a few weeks ago:

http://groups.google.com/group/micro...f9a992875ff74e

:-)

Arne
Jun 27 '08 #7
On Jun 24, 1:38*am, Arne Vajhøj <a...@vajhoej.dkwrote:
Dictionary<int,List<Person>peopleByAge =
* * new Dictionary<int,List<Person>>();
(Yes, I had to wrap onto two lines because it's so long...)
vs
var peopleByAge = new Dictionary<int,List<Person>>();
Which one do you prefer? What's the benefit of the redundancy here?

I prefer the first one as we discussed a few weeks ago:
<snip>

And that's fair enough - we can have a reasonable discussion about the
pros and cons of it, even though in the end it's largely a matter of
personal taste. The important thing is that it's a more sensible
example than the one Frans provided. Giving a "worst possible" use of
a feature doesn't give evidence against using that feature in other
situations.

Jon
Jun 27 '08 #8
Jon Skeet [C# MVP] wrote:
On Jun 24, 1:38 am, Arne Vajhøj <a...@vajhoej.dkwrote:
>>Dictionary<int,List<Person>peopleByAge =
new Dictionary<int,List<Person>>();
(Yes, I had to wrap onto two lines because it's so long...)
vs
var peopleByAge = new Dictionary<int,List<Person>>();
Which one do you prefer? What's the benefit of the redundancy here?
I prefer the first one as we discussed a few weeks ago:

<snip>

And that's fair enough - we can have a reasonable discussion about the
pros and cons of it, even though in the end it's largely a matter of
personal taste. The important thing is that it's a more sensible
example than the one Frans provided. Giving a "worst possible" use of
a feature doesn't give evidence against using that feature in other
situations.
That last remark is too generic to be valuable. The main point is that
if you (one in general) give out advice that 'var' is actually often
better, there are serious consequences to be realized as well. Your
dictionary example isn't disturbing me at all, though using 'var' is.
During writing linq queries I often realized I was mousing over
variables to see what type they had. I find that a sign that something
is wrong.

If you aren't disturbed by that, that's of course your own choice,
however do realize that if you have to read code outside VS.NET, you
should be able to do that, easily, and without running the risk of
making assumptions which might not be correct.

FB

--
------------------------------------------------------------------------
Lead developer of LLBLGen Pro, the productive O/R mapper for .NET
LLBLGen Pro website: http://www.llblgen.com
My .NET blog: http://weblogs.asp.net/fbouma
Microsoft MVP (C#)
------------------------------------------------------------------------
Jun 27 '08 #9
On Jun 24, 8:48*am, "Frans Bouma [C# MVP]"
<perseus.usenetNOS...@xs4all.nlwrote:
* * * * That last remark is too generic to be valuable. The main point is that
if you (one in general) give out advice that 'var' is actually often
better, there are serious consequences to be realized as well. Your
dictionary example isn't disturbing me at all, though using 'var' is.
During writing linq queries I often realized I was mousing over
variables to see what type they had. I find that a sign that something
is wrong.
Would you have to mouse over the variable to find its type with the
"var" case?

I know I find it just as easy to look to the right of the declaration
as to the left. There are far more "grey area" cases of course, where
some people would find a method call's return type obvious and some
wouldn't - but for a constructor call it seems pretty obvious to me.
* * * * If you aren't disturbed by that, that's of course your own choice,
I'd be disturbed if I found myself doing it, but I don't think I'd
start hovering over variables where the constructor call is clearly
visible... unless the declaration wasn't visible either, of course, in
which case it doesn't matter whether you're using var or not.
however do realize that if you have to read code outside VS.NET, you
should be able to do that, easily, and without running the risk of
making assumptions which might not be correct.
Again, would you really not be able to understand the RHS of my
example?

Jon
Jun 27 '08 #10
Please go to http://www.a2zdotnet.com/Default.aspx
for step by step tutorials for beginers in LINQ sections.

--
regards,
Pankaj
http://www.A2ZDotNet.com
"da**********@yahoo.com.au" wrote:
Hi, I have the following code extract...
---top---

List<PersonPersons = new List<Person>();
Persons.Add(new Person("Peter", 28,"Perth"));
Persons.Add(new Person("Matthew", 31, "Bundaberg"));
Persons.Add(new Person("Cathryn", 36, "Perth"));
//This works
IEnumerable<Personp1 = from op in Persons
where op.City=="Perth"
select op;

//Tut this doesn't work
List<Personp2 = from op in Persons
where op.City == "Perth"
select op;
---bottom---
The compiler error message is: Compiler Error Message: CS0266: Cannot
implicitly convert type
'System.Collections.Generic.IEnumerable<ASP.linq_l inqgrouping_aspx.Person>'
to
'System.Collections.Generic.List<ASP.linq_linqgrou ping_aspx.Person>'.
An explicit conversion exists (are you missing a cast?)

I'm trying to not get into the habit of using var because I read
somewhere (MSDN) that it makes your code more unreadable to others,
which I tend to agree with.

Can someone please tell me what I'm doing wrong?

Thanks in advance,
Damien
Aug 11 '08 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

28
by: Marc Gravell | last post by:
In Linq, you can apparently get a meaningful body from and expression's .ToString(); random question - does anybody know if linq also includes a parser? It just seemed it might be a handy way to...
4
by: BeSharp | last post by:
I recently stumbled across a pretty interesting LINQ to SQL question and wonder, whether anybody might have an answer. (I'm doing quite some increasing LINQ evangelism down here in Germany.). ...
3
by: zacks | last post by:
I am trying to get into LINQ. I have created ConsoleApplication project and have pasted in the code from one of the examples in help: DataContext db = new DataContext(@"c:\program files...
1
by: shapper | last post by:
Hi, I wonder, is there some tool that transforms SQL procedures to LINQ? :-) I want to use LINQ but I have so much work done in SQL that would be great to transform my SQL code to LINQ. ...
9
by: =?Utf-8?B?cmF1bGF2aQ==?= | last post by:
Hi all: after reading different places/sites about linq... I ran into these questions: 1. What framework do we need to run linq ? (does it depend on what version of visual studio we have?) how...
1
by: =?Utf-8?B?RGF2aWRHQg==?= | last post by:
OK, so I've created and loaded an XMLDocument object. But how do I go about using it? Specifically, how do I: 1) move to the first node (I assume I start on it when I load the XML?) 2) move to...
4
by: CSharper | last post by:
I have following XML <root> <Person id="1"> <Name>a</Name> </Person> <Person id="2"> <Name>b</Name> </Person> </root>
3
by: =?Utf-8?B?UGF1bCBQcmV3ZXR0?= | last post by:
I'm attempting to use LINQ to insert a record into a child table and I'm receiving a "Specified cast is not valid" error that has something to do w/ the keys involved. The stack trace is: ...
0
by: balint kardos | last post by:
Hi all, My question is about parsing and saving a LINQ query from/to xml. I'm creating an web interface where a user can select fields from dataset tables, and create relations between them...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.