我有一個屏幕附在這裏,我需要知道我怎麼可以將列表轉換爲長列表?將此var轉換爲長整型列表?
var x = SchedulerMatrixStorage.Resources.Items.Select(col => col.Id);
其中,編號爲類型的Object
我有一個屏幕附在這裏,我需要知道我怎麼可以將列表轉換爲長列表?將此var轉換爲長整型列表?
var x = SchedulerMatrixStorage.Resources.Items.Select(col => col.Id);
其中,編號爲類型的Object
由於您的清單似乎是同質的,你可以利用這一點是.NET框架的一部分內置轉換功能:
var x = SchedulerMatrixStorage.Resources.Items
.Select(col => Convert.ToInt64(col.Id)).ToList();
Convert
靜態類提供了幾個轉換函數,其中一組將把各種類型的對象轉換爲各種內置值類型,如long
。大多數這些功能也有一個超載,需要一個object
參數(我假設你的收藏基本包含)。
注意,這個函數會在運行時,如果所提供的對象是什麼,不能轉換成long
(比如,如果你要傳遞,比如說,一個Form
),但你的截圖來看這會失敗爲你工作。
您可以在Select
語句中使用long.Parse()
,因爲從你的截圖它看起來像值Items
集合中可能是字符串:
var x = SchedulerMatrixStorage.Resources.Items.Select(col =>
long.Parse(col.Id.ToString())).ToList();
x
將被解析爲鍵入System.Collections.Generic.List<long>
。
認爲這應該做你想做的
var x = SchedulerMatrixStorage.Resources.Items.Select(col => col.Id).Cast<long>().ToList();
與同樣的答案一樣,這會對他失敗。他的第一個項目是一個字符串。 – 2011-03-14 17:43:13
也許是最快捷的方法是這樣的:
var x = SchedulerMatrixStorage.Resources.Items.Select(col => col.Id).Cast<long>();
雖然你應該確保你只得到了ID所不久便前裝箱作爲一個對象。
這會因提供的值而失敗,因爲第一個字符串是字符串。 – 2011-03-14 17:42:53
如果Id
是object
類型,但值始終是一個字符串,你可以使用:
var x = SchedulerMatrixStorage.Resources
.Items
.Select(col => long.Parse((string)col.Id)
.ToList();
但是,目前還不清楚的是,結果總是是一個字符串。您需要提供更多關於col.Id
的信息。
一般情況下,你想是這樣的:
var x = SchedulerMatrixStorage.Resources
.Items
.Select(ConvertColumnId)
.ToList();
private static long ConvertColumnId(object id)
{
// Do whatever it takes to convert `id` to a long here... for example:
if (id is long)
{
return (long) id;
}
if (id is int)
{
return (int) id;
}
string stringId = id as string;
if (stringId != null)
{
return long.Parse(stringId);
}
throw new ArgumentException("Don't know how to convert " + id +
" to a long");
}
嗯,我設法將第一個字符串"-1"
轉換爲合適的長度。行var x = SchedulerMatrixStorage.Resources.Items.Select(col => Convert.ToInt64(col.Id)).ToList();
現在適合我。身份證將永遠是一個長期的。有了這個規則,有沒有最好的方法來完成這個?我的意思是,我的任務已經完成,但希望現在如果LINQ提供一個更好的方法...
發佈答案時,您無法提出新問題。當你發佈答案時,沒有人會收到通知,所以沒有人會看到這一點。問一個新問題,或者添加一個評論給別人的答案,提到他的名字,像這樣:@Hassan。 – 2011-03-17 04:16:35
謝謝@ilyakogan – DoomerDGR8 2011-03-17 15:53:10
爲什麼'Parse'?我認爲這是對象,而不是一個字符串。 – 2011-03-14 17:22:42
無論如何,如果所有對象的類型都是'long','Parse'優於'Cast'的優點是什麼? – 2011-03-14 17:22:56
@gaearon他的第一項是:'「-1」',這是一個字符串。 – CodingGorilla 2011-03-14 17:23:41