Doing maths with contents of 2 files.

Tiaan

Member
Joined
Mar 25, 2015
Messages
15
Programming Experience
1-3
I have 2 text files, both comma deliminated, and decimal values.
I used an string array to read all the contents in and to split it at each comma.

I need to take the first value from file1 and subtract it from the first value in file 2.

Do i need to convert the arrays to integers or am i totally wrong?
 
While you can, you don't need the arrays to be numeric data type, but you do need to convert each string value to a numeric data type before doing the math calculation.
 
If you are using .NET 3.5+, you can use the IEnumerable.Cast(Of T) method to cast your array of numeric strings to a lazy loading enumerable of integers (or doubles, etc). The advantage here is you do it all in one line of code and it casts each value only when you read it.

Dim lazyLoadingIntEnumerable = someNumericStringArray.Cast(Of Integer)()
 
If you are using .NET 3.5+, you can use the IEnumerable.Cast(Of T) method to cast your array of numeric strings to a lazy loading enumerable of integers (or doubles, etc). The advantage here is you do it all in one line of code and it casts each value only when you read it.

Dim lazyLoadingIntEnumerable = someNumericStringArray.Cast(Of Integer)()
Actually not, Cast does only do type casts, not conversions, and String can't be cast as Integer so you need to convert it to integer, but you can use Array.ConvertAll:
Dim integers = Array.ConvertAll(stringnumberarray, Function(num) CInt(num))

or if you want lazy conversion:
Dim integers2 = stringnumberarray.Select(Function(num) CInt(num))

About "lazy", if you try to access an item in the enumerable result by index that would cause each item before it to be converted as well, it would work fine for a single or few For Each loop iterations, but if you for example used it to compare two lists index by index that would be very inefficient. For example 2*10 items lists compared by index 0 to 9 would mean there will be 110 conversions instead of just 20.
As for Linq, if you want to perform such operations and want only one execution, then you can convert the query result to array with ToArray extension and use that in later calculations.
 
Back
Top