Linq Query : Cannot convert type IEnumerable<string> to string changing .ToString() to (string)

匿名 (未验证) 提交于 2019-12-03 00:50:01

问题:

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'

回答1:

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() 


回答2:

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.



回答3:

Try this worked for me :

 var returnCollection = (from manager in list.Employee       select manager).ToList(); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!