Reputation:
I have a linq query that contains
select new Project()
{
Manager = list.Employee.Select(x => x.Manager).ToString()
}).ToList();
This COMPILES, but I don't end up with the data...
I get value for "Manager" of System.Linq.Enumerable+WhereSelectListIterator<Flex.Data.Systems,System.String>
So I thought I would change to (string)
instead of .ToString()
but this does not work
select new Project()
{
Manager = (string)list.Employee.Select(x => x.Manager)
}).ToList();
Gives me the error message
Cannot convert type 'System.Collections.Generic.IEnumerable' to 'string'
I need it to be a collection, so that when I pass back out my List<Project>
that Manager
contains many Managers.
Upvotes: 6
Views: 28235
Reputation: 624
Whenever you make a selection of columns from a collection it will return a collection. Even if you specify a where clause to match an exact record.
For your case, you can have them converted to
Manager = list.Employee.Select(x => x.Manager).ToList()
or
Manager = list.Employee.Select(x => x.Manager).ToArray()
This is what Tim told above.
There could be case where you get a collection and you are sure that the first one is what you need. For that you can always use:
Manager = list.Employee.Select(x => x.Manager).First();
Note: This might throw an error if there is nothing found as a collection along with where clause used. In such case use:
Manager = list.Employee.Select(x => x.Manager).FirstOrDefault();
This will not give error even if noting is returned matching.
Upvotes: 0
Reputation: 844
Try this worked for me :
var returnCollection = (from manager in list.Employee
select manager).ToList();
Upvotes: 0
Reputation: 46947
The problem is that list.Employee.Select(x => x.Manager)
returns a collection of managers and property Manager
is a string (?). You need some condition of which manager you want. For example append .First()
to get the first one in the collection.
Upvotes: 7
Reputation: 460158
What do you want Manager
to be, a string
with a comma separated list of values or a List<string>
/String[]
?
string:
Manager = string.Join(",",list.Employee.Select(x => x.Manager))
collection:
Manager = list.Employee.Select(x => x.Manager).ToList()
// or
Manager = list.Employee.Select(x => x.Manager).ToArray()
Upvotes: 11