将通用列表转换为字符串列表 [英] convert generic list to string list
本文介绍了将通用列表转换为字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一种方法可以将通用列表转换为列表...我试过这样,但我得到一个异常....请帮助
Is there a way to convert a generic list to list...I tried like this but I get an exception....Please help
Class Demo
{
public list<string> convert()
{
List<example> eg = new List<example>();
eg.Add(new example{"Hello"});
eg.Add(new example{"World"});
List<string> str = new List<string>();
str = eg.Cast<string>().ToList(); //Returns an System.InvalidCastException.
// Is there a way to cast a generic list to string list..
return str;
}
}
Class example
{
public string name{ get; set; }
}
推荐答案
投影,而不是投。这是因为您的示例
类不能转换为 string
。在LINQ中,投影由选择
方法执行:
What you need is a projection, not a cast. That's because your example
class cannot be casted to string
. In LINQ, projection is done by Select
method:
return eg.Select(x => x.name).ToList();
这篇关于将通用列表转换为字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文