C# 在 .NET 2.0 中将 List<int> 转换为 List<string>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cast List<int> to List<string> in .NET 2.0
提问by lomaxx
采纳答案by Glenn Slaven
.NET 2.0 has the ConvertAll
method where you can pass in a converter function:
.NET 2.0 有一个ConvertAll
方法,你可以传入一个转换器函数:
List<int> l1 = new List<int>(new int[] { 1, 2, 3 } );
List<string> l2 = l1.ConvertAll<string>(delegate(int i) { return i.ToString(); });
回答by Erik van Brakel
Is C# 2.0 able to do List<T>.Convert
? If so, I think your best guess would be to use that with a delegate:
C# 2.0 能做到List<T>.Convert
吗?如果是这样,我认为您最好的猜测是将其与委托一起使用:
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Convert(delegate (int i) { return i.ToString(); });
Something along those lines.
沿着这些路线的东西。
Upvote Glenn's answer, which is probably the correct code ;-)
赞成格伦的回答,这可能是正确的代码 ;-)
回答by Curt Hagenlocher
You have to build a new list. The underlying bit representations of List<int>
and List<string>
are completely incompatible -- on a 64-bit platform, for instance, the individual members aren't even the same size.
你必须建立一个新的列表。的根本比特表示List<int>
并List<string>
完全兼容-在64位平台上,例如,个别成员甚至不相同的大小。
It is theoretically possible to treat a List<string>
as a List<object>
-- this gets you into the exciting worlds of covariance and contravariance, and is not currently supported by C# or VB.NET.
理论上可以将 aList<string>
视为 a List<object>
—— 这让您进入了令人兴奋的协变和逆变世界,并且当前不受 C# 或 VB.NET 支持。
回答by ljs
You wouldn't be able to directly cast it as no explicit or implicit cast exists from int to string, it would haveto be a method involving .ToString() such as:-
您将无法直接转换它,因为从 int 到字符串不存在显式或隐式转换,它必须是涉及 .ToString() 的方法,例如:-
foreach (int i in intList) stringList.Add(i.ToString());
Edit- or as others have pointed out rather brilliantly, use intList.ConvertAll(delegate(int i) { return i.ToString(); });, however clearly you still have to use .ToString() and it's a conversion rather than a cast.
编辑- 或者正如其他人非常出色地指出的那样,使用 intList.ConvertAll(delegate(int i) { return i.ToString(); });,但很明显你仍然必须使用 .ToString() 并且它是一个转换而不是一个演员。
回答by Luke
Updated for 2010
2010 年更新
List<int> l1 = new List<int>(new int[] { 1,2,3 } );
List<string> l2 = l1.ConvertAll<string>(x => x.ToString());
回答by lutecki
You can use:
您可以使用:
List<int> items = new List<int>(new int[] { 1,2,3 } );
List<string> s = (from i in items select i.ToString()).ToList();
回答by Jayant Rajwani
result = listOfInt.Select(i => i.ToString(CultureInfo.InvariantCulture)).ToList()
result = listOfInt.Select(i => i.ToString(CultureInfo.InvariantCulture)).ToList()
replace the parameters result and listOfInt to your parameters
将参数 result 和 listOfInt 替换为您的参数