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.
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 .
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);
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.