dgrant
dgrant

Reputation: 1427

"The best overloaded Add method 'System.Collections.Generic.List.Add(System.Guid)' for the collection initializer has some invalid arguments"

List<PageInfo> subPages = new List<PageInfo>();
// ...
// some code to populate subPages here...
// ...
List<Guid> subPageGuids = new List<Guid> {from x in subPages select x.Id}; //doesn't work

PageInfo has an Id field which is of type Guid. So x.Id is a System.Guid.

2nd line of code above does not work...I get errors:

The best overloaded Add method 'System.Collections.Generic.List.Add(System.Guid)' for the collection initializer has some invalid arguments

And

Argument '1': cannot convert from 'System.Collections.Generic.IEnumerable' to 'System.Guid'

I've only been coding in C# for about a week, but I've done a similar pattern before and never had this problem.

Upvotes: 2

Views: 8256

Answers (3)

Stormenet
Stormenet

Reputation: 26468

It looks like the Add() is called and not AddRange().

You could use this syntax instead:

List<Guid> subPageGuids = (from x in subPages select x.id).ToList();

or

List<Guid> subPageGuids = new List<Guid>();
subPageGuids.AddRange(from x in subPages select x.id);

Upvotes: 2

AwesomeTown
AwesomeTown

Reputation: 2880

I think you want:

List<Guid> subPageGuids = new List<Guid>(from x in subPages select x.Id);

(note the curly braces changed to regular braces)

That will call the constructor of List that takes an IEnumerable (which is what the linq query returns) as a parameter. Right now you're trying to use the syntax for an object initializer.

Upvotes: 8

davogones
davogones

Reputation: 7399

You're using a list initializer here incorrectly. The compiler is expecting you to put single Guids in the brackets, not a list of Guids. Here is what you need to do:

List<Guid> subPageGuids = (from x in subPages select x.Id).ToList();

Upvotes: 2

Related Questions