heyred
heyred

Reputation: 2051

Converting from List<float> to int

Can anyone please tell me if this can be done, and if yes, how?

I have a List<float> FocalLengthList that I have populated with some values. Then THIS List is stored in a List<List<float>> MainFocalLenghtList. However, in my application I need to use the values fromMainFocalLenghtList to update an objects 3D position. So I need to cast fromMainFocalLenghtList [0] to int.

Can this be done and how?

Here is a small section of my code to explain. Adding values to FocalLengthList then adding that list to List<List<float>> MainFocalLenghtList

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

Then how I intend to use the values (not working)

int zComponent = MainFocallengthList[0];

Upvotes: 1

Views: 2335

Answers (5)

L.B
L.B

Reputation: 116178

Since MainFocalLengthList is a List of List<float>

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

Upvotes: 1

James Johnson
James Johnson

Reputation: 46067

Give this a shot:

var floatList = new List<float>();

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

Upvotes: 1

Dan J
Dan J

Reputation: 16718

You can certainly cast a float to an int, as long as you do so explicitly (since it may involve a loss of precision).

The problem with the code you've posted is that you're indexing into a list of other lists. The value returned by MainFocallengthList[0] will itself be a List<float>. You must then index into that list to get a value you can actually cast to int.

Assuming both the target list and the target float in that list are at the first index of their respective containers:

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

That first index returns the FocalLengthList that you added to MainFocalLengthList. The second index returns the newFocalLength value that you added to FocalLengthList. Clear? :)

Upvotes: 3

Chris Shain
Chris Shain

Reputation: 51369

You can do it this way, but you need the indexes of both the inner and outer lists:

// 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])

Upvotes: 0

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107606

I'd probably do it like this:

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

Though you'll want to substitute actual values for the nth item in the mth FocalLengthList.

Upvotes: 1

Related Questions