2012-04-09 146 views
1

任何人都可以告訴我,如果這可以做到,如果是的話,怎麼樣?從列表<float>轉換爲int

我有一個List<float> FocalLengthList,我已經填充了一些值。然後,這個列表被存儲在List<List<float>> MainFocalLenghtList中。 但是,在我的應用程序中,我需要使用來自MainFocalLenghtList的值來更新對象3D位置。所以我需要將fromMainFocalLenghtList [0]轉換成int

可以這樣做,怎麼樣?

這是我的代碼的一小部分來解釋。 增加值FocalLengthList然後加入該列表List<List<float>> MainFocalLenghtList

float newFocalLength = focalLength * pixelSize; 
FocalLengthList.Add(newFocalLength); 
MainFocallengthList.Add(FocalLengthList); 
FocalLengthList = new List<float>(); 

然後我打算如何使用這些值(不工作)

int zComponent = MainFocallengthList[0]; 
+0

你們是不是要投單浮到單個int或整個列表到列表的整數?你的問題並不清楚。 – 2012-04-09 20:34:28

+0

我正要問同樣的事情。 – MilkyWayJoe 2012-04-09 20:34:50

+2

MainFocallenthList是列表的列表。如果你將一個浮點數列表賦給一個int,你會期望結果如何? – Robaticus 2012-04-09 20:35:07

回答

0

你能做到這樣,但是你既需要內部和外部列表的指標:

// The first [0] indicates the index of the nested list within MainFocallengthList 
// The second [0] indicates the index of the item that you want in the nested list 
int zComponent = (int)(MainFocallengthList[0][0]) 
1

我可能會做這樣的:

int zComponent = (int)Math.Ceiling(MainFocallengthList[m][n]); 

雖然您想要替換實際值nth項目mthFocalLengthList

3

可以肯定蒙上floatint,只要你明確地這樣做(因爲它可能涉及精確度的損失)。

您發佈的代碼的問題在於,您正在將其他列表的列表編入索引。由MainFocallengthList[0]返回的值本身將爲List<float>。然後你必須索引到列表才能得到一個你可以實際轉換爲int的值。

假設兩個目標列表和目標浮動,列出均爲其各自容器的第一索引:

int zComponent = (int)MainFocalLengthList[0][0]; 

,首先指數回報您添加到MainFocalLengthListFocalLengthList。第二個索引返回您添加到FocalLengthList的值newFocalLength。明確? :)

1

這給一個鏡頭:

var floatList = new List<float>(); 

var intList = floatList.Select(f => (int)Math.Ceiling(f)).ToList(); 
1

由於MainFocalLengthList是一個List List<float>

var intarr = Array.ConvertAll(MainFocalLengthList[0].ToArray(), f=>(int)f);