tags:

views:

144

answers:

3
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 two errors:

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

  • 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.

+2  A: 

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);
Stormenet
+2  A: 

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();
davogones
+8  A: 

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.

John Price
Thanks! That explains why when I looked at the other times I've used this pattern it looked like I was doing the exact same thing. My eyes weren't differentiating between the curlies and the braces. I've been using Python for too long I guess.
dgrant