字符串转换使用LINQ to int数组 [英] Convert string to int array using LINQ
问题描述
可能重复:
<一href=\"http://stackoverflow.com/questions/2113115/c-is-there-a-linq-way-to-create-an-array-of-objects-given-an-array-of-construc\">C#:有没有LINQ的方式来创建特定的构造函数的参数数组对象的数组?
块引用>我有一个函数(tointarray)将字符串转换成int数组,但我不是很满意。它的工作,但必须有一个更优雅的方式来做到这一点,或许 LINQ可以在这里帮助。可惜我不是在LINQ非常好。有没有更好的办法?
我的功能:
{
字符串S1 =1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12;
INT [] IA = tointarray(S1';');
}
INT [] tointarray(字符串值,字符SEP)
{
字符串[] SA = value.Split(SEP);
INT [] IA =新INT [sa.Length]
的for(int i = 0; I&LT; ia.Length ++ I)
{
诠释J;
字符串s = SA [我]
如果(int.TryParse(S,出j)条)
{
IA [I] = j的;
}
}
返回IA;
}
解决方案<一个href=\"http://stackoverflow.com/questions/2113115/c-is-there-a-linq-way-to-create-an-array-of-objects-given-an-array-of-construc\">This后问过类似的问题,使用LINQ来解决它,也许它会帮助你了。
字符串S1 =1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12;
INT [] IA = s1.Split(';')选择。(N =&GT; Convert.ToInt32(N))ToArray的();Possible Duplicate:
C#: Is there a LINQ way to create an array of objects given an array of constructor parameters?I have a function (tointarray) to convert a string into an array of ints, but I am not very satisfied with it. It does the job, but there must be a more elegant way to do this, and perhaps LINQ could help here. Unfortunately I am not very good in LINQ. Is there a better way?
My function:
{ string s1 = "1;2;3;4;5;6;7;8;9;10;11;12"; int[] ia = tointarray(s1, ';'); } int[] tointarray(string value, char sep) { string[] sa = value.Split(sep); int[] ia = new int[sa.Length]; for (int i = 0; i < ia.Length; ++i) { int j; string s = sa[i]; if (int.TryParse(s, out j)) { ia[i] = j; } } return ia; }
解决方案This post asked a similar question and used LINQ to solve it, maybe it will help you out too.
string s1 = "1;2;3;4;5;6;7;8;9;10;11;12"; int[] ia = s1.Split(';').Select(n => Convert.ToInt32(n)).ToArray();
这篇关于字符串转换使用LINQ to int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!