回答
var values = new string[] { "1", "2", "3" };
values.Select(x => Int32.Parse(x)).ToArray();
Int32.TryParse是更快的Int32.Parse – 2010-06-21 10:00:10
而這實際上並沒有給一個數組......並且不是填充這樣一個數組的「最快」(問題)方式。但除此之外...... – 2010-06-21 10:02:51
a)它返回的數據結構與您要求的不同,b)Marc Gravell的答案比其他人在這裏的答案要好一個數量級? – 2010-06-21 10:02:59
迭代和轉換。
我建議迭代和int.TryParse()
Which one is faster in processing and conversion int.Parse(), int.TryParse(), Convert.Int32()
請參閱Microsoft Parse , TryParse and ConvertTo
的比較是我知道有沒有快速的方式,但你可以用一個「短的路「:
var numbers = new[] {"1", "2", "3"};
var result = numbers.Select(s => int.Parse(s));
int[] resultAsArray = result.ToArray();
如果你使用PLINK,你可以並行計算值。
string[] arr1 = {"1","2","3"};
int[] arr2 = Array.ConvertAll(arr1, s => int.Parse(s));
採用Array.ConvertAll
確保(不同於LINQ Select
/ToArray
),該陣列是在合適大小初始化。你可以儘可能獲得遮陽更快的展開,但並不多:
int[] arr2 = new int[arr1.Length];
for(int i = 0 ; i < arr1.Length ; i++) {
arr2[i] = int.Parse(arr[i]);
}
如果你需要的東西更快還是(或許是大容量文件/數據處理),然後寫自己的解析可以幫助;內置的處理很多的邊緣情況 - 如果你的數據更簡單,你真的可以減少這一點。
另一種可選擇的解析器的例子:
public static unsafe int ParseBasicInt32(string s)
{
int len = s == null ? 0 : s.Length;
switch(s.Length)
{
case 0:
throw new ArgumentException("s");
case 1:
{
char c0 = s[0];
if (c0 < '0' || c0 > '9') throw new ArgumentException("s");
return c0 - '0';
}
case 2:
{
char c0 = s[0], c1 = s[1];
if (c0 < '0' || c0 > '9' || c1 < '0' || c1 > '9') throw new ArgumentException("s");
return ((c0 - '0') * 10) + (c1 - '0');
}
default:
fixed(char* chars = s)
{
int value = 0;
for(int i = 0; i < len ; i++)
{
char c = chars[i];
if (c < '0' || c > '9') throw new ArgumentException("s");
value = (value * 10) + (c - '0');
}
return value;
}
}
}
關於ConvertAll的有趣點,不知道! – 2010-06-21 09:53:19
我可能會做的事:
string[] array = new[] { "1", "2" }; // etc.
int[] ints = array.Select(x => int.Parse(x)).ToArray();
如果我能保證數據將只有整數。
如果不是:
string[] array = new[] { "1", "2" }; // etc.
List<int> temp = new List<int>();
foreach (string item in array)
{
int parsed;
if (!int.TryParse(item, out parsed))
{
continue;
}
temp.Add(parsed);
}
int[] ints = temp.ToArray();
string[] arr = new string[]{ "1", "2", "3" };
int[] lss = (from xx in arr
select Convert.ToInt32(xx)).ToArray();
- 1. 將字符串轉換爲int,int轉換爲字符串
- 2. 轉換INT [] []將字符串
- 3. 將字符串轉換爲int數組
- 4. 將字符串轉換爲int []
- 5. 將字符串轉換爲空值int
- 6. 將字符串轉換爲int陣列
- 7. 如何將字符串轉換爲int
- 8. 如何將字符串轉換爲Int?
- 9. 如何將字符串轉換爲int?
- 10. 將字符串轉換爲int在C++
- 11. SSRS將Int轉換爲字符串
- 12. LINQ將字符串轉換爲int
- 13. 而將字符串轉換爲int後
- 14. C:將int []轉換爲字符串
- 15. 將int轉換爲字符串數組
- 16. JAQL將int轉換爲字符串
- 17. 將字符串轉換爲int - datareader
- 18. 將JTextField字符串轉換爲Int
- 19. 將int和char轉換爲字符串
- 20. C:將int轉換爲字符串
- 21. 將字符串類型轉換爲int
- 22. 將int轉換爲字符串
- 23. 將DataSet轉換爲字符串或Int
- 24. 將arraylist int轉換爲字符串
- 25. 將字符串轉換爲int(C++)
- 26. C++將字符串轉換爲int
- 27. 將字符串轉換爲顏色int
- 28. 將字符串空值轉換爲int
- 29. 將字符串轉換爲int(2)
- 30. 將字符串轉換爲long long int
是肯定的項目僅在字符串格式的整數? – 2010-06-21 09:43:10
是的,只有整數 – 2010-06-21 09:43:55
查看http://stackoverflow.com/questions/1297231/convert-string-to-int-in-one-string-of-code-using-linq – abatishchev 2010-06-21 09:49:32