2009-11-30 42 views
0

我從下面的代碼片段獲得這個 Unable to cast object of type 'System.Int64' to type 'System.String'. 列表獲取一個字符串數組:LINQ Bug?從長期

IList<long> Ids = new List<long>(); 
Ids.Add(6962056); 
Ids.Add(7117210); 
Ids.Add(13489241); 

var stringIds = Ids.Cast<string>().ToArray(); 

和Booooooooooooom ....想法?

回答

7

你不能長到一個字符串。您需要指定要執行什麼操作才能將長整型轉換爲字符串。我更喜歡使用Linq來選擇新的值:

var stringIds = Ids.Select(id => id.ToString()); 
+0

所以,你必須選擇/轉換的源值...我想CAST()是一次聰明得多的字符串是目標類型,它應該簡單地在源類型上自行調用.ToString()。 – 2009-12-01 09:00:41

1

那是因爲你不能將longs轉換爲字符串。

你混淆

long l = 10; 
string s = (string)l; // this will not work, l is not a string 

long l = 10; 
string s = l.ToString(); // this will work 
+0

這清除了什麼.Cast ()正在做什麼。我認爲這是調用.ToString()...所以謝謝你的解釋。 – 2009-12-01 08:54:49