tags:

views:

416

answers:

2

When assigning a linq selection to an implicitly typed local variable "var" i receive the following error.

Error :Cannot assign method group to an implicitly-typed local variable

at

root : var mailgroup = emails.Where(p =>IsValidFormat(p.Value)).Select;

Dictionary of elements

        Dictionary<int, string> emails = new Dictionary<int, string>();
        emails.Add(1, "[email protected]");
        emails.Add(2, "[email protected]");
        emails.Add(3, "Rose");
        emails.Add(4, "Ana");
        emails.Add(5, "[email protected]");
        Dictionary<int, string> dc = new Dictionary<int, string>();

How to correct it ?

+10  A: 

What are you expecting it to do? You probably want to make an actual method call there, such as:

var mailgroup = emails.Where(p =>IsValidFormat(p.Value))
                      .Select(p => p.Value);

Or if you just want the key/value pairs, you can just use:

var mailgroup = emails.Where(p =>IsValidFormat(p.Value));

and remove the "Select" entirely.

If you do just want the values (as per the first code snippet) I'd suggest using:

var mailgroup = emails.Values.Where(p =>IsValidFormat(p));

Without any brackets, your reference to "Select" is a method group - the kind of thing you'd convert to a delegate, e.g.

Func<int> x = SomeMethod; // Where SomeMethod is declared as "int SomeMethod()"

It doesn't really make sense to use Select as method group in this case, although it is just about feasible...

Jon Skeet
Oops , :( How bad i am !!!!!!!!!!!! Thanks Mr Jon
What prevents me from giving votes?
@geneliaa: I suspect you didn't have enough reputation. Try again now.
Jon Skeet
Wow. I registered my first vote to my favorite C# author(C# in depth).
Did you just give someone an upvote just so he could give you one? I think that's taking rep-whoring way too far.
Joren
@Joren: Just how much rep do you believe a vote gives me at this time of day? It's about 14 hours too late...
Jon Skeet
I have no idea what timezone you're in. I'm sorry for jumping to conclusions about your intentions, but this just looked way weird.
Joren
@Joren: My time zone is irrelevant. The reputation cap is applied in UTC.
Jon Skeet
+5  A: 

You're missing () after Select. As a result, what's being assigned to the variable is a reference to the Select method, which the compiler refers to as a 'method group'.

Incidentally, based on the code that you've posted I don't think that you need the trailing .Select() at all.

JSBangs
There are no parameterless overloads for Select though - he'll need to put *something* in there.
Jon Skeet
(An empty select statement *isn't* valid.)
Jon Skeet
Yeah... I double-checked and removed that statement while you were posting your comment.
JSBangs