How to convert string array to int array to make calculation? - c#

I want to read the integers after the /. thats why i tried to use this code:
while ((line = file.ReadLine()) != null)
{
string[] ip = line.Split('/');
Console.WriteLine(ip[1]);
}
this code returns me this integers as string. I want to some math calculation with this numbers ,for example, multiplication. I tried this code but it doesnt work
int[] intArray = Array.ConvertAll(ip, int.Parse);

You are trying to convert each item of ip array to integer. At lease second item of it - "24 25 26 27" cannot be converted to single integer value. You should take this item of ip array, split it by white space and then parse each part to integer:
int[] intArray = ip[1].Split().Select(Int32.Parse).ToArray();
Or
int[] intArray = Array.ConvertAll(ip[1].Split(), Int32.Parse);

If its really about IP-Adresses, this might help
class IPV4Adress
{
public int BlockA {get; set;}
public int BlockB {get; set;}
public int BlockC {get; set;}
public int BlockD {get; set;}
public IPV4Adress(string input)
{
If(String.IsNullOrEmpty(input))
throw new ArgumentException(input);
int[] parts = input.Split(new char{',', '.'}).Select(Int32.Pase).ToArray();
BlockA = parts[0];
BlockB = parts[1];
BlockC = parts[2];
BlockD = parts[3];
}
public override ToString()
{
return String.Format("{0}.{1}.{2}.{3}",BlockA, BlockB, BlockC, BlockD);
}
}
Then read it from File:
IPV4Adress[] adresses = File.ReadLines(fileName).SelectMany(line=>line.Split('/')).Select(part => new IPV4Adress(part)).ToArray();

Given an array you can use the Array.ConvertAll method:
int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));
(or)
int[] myInts = arr.Select(s => int.Parse(s)).ToArray();
(Or)
var converted = arr.Select(int.Parse)
A LINQ solution is similar, except you would need the extra ToArray call to get an array:
int[] myInts = arr.Select(int.Parse).ToArray();
Sourec

Related

Get input array of particular type

I need to get array input in particular types - example for int below.
string[] input = Console.ReadLine().Split(' ');
int[] array = new array[input.Length];
for(int i = 0; i < input.Length; i++)
{
array[i] = int.Parse(input[i]);
}
This is working, but in case of multiple such arrays of different type it takes up too much code to get input in string array and then parse it into required type for every input array.
Is there any shortcut way to get this done ?
It is guaranteed that complete array input will lie on single line.
Have a look at Enumerable.Select:
int[] array = input.Select(int.Parse).ToArray();
You could easily change this to another type, for example:
class StringContainer
{
public string Value { get; set; }
}
StringContainer[] array = input.Select(x => new StringContainer { Value = x }).ToArray();
You could even define an extension method:
public static TOut[] Convert<TIn, TOut>(this TIn[] input, Func<TIn, TOut> selector)
{
return input.Select(selector).ToArray();
}
Then use like this:
int[] intArray = input.Convert(int.Parse);
StringContainer[] scArray = input.Convert(x => new StringContainer { Value = x });
The type of the output array is inferred from the return type of the delegate.

C# Populate An Array with Values in a Loop

I have a C# console application where an external text file is read. Each line of the file has values separated by spaces, such as:
1 -88 30.1
2 -89 30.1
So line one should be split into '1', '-88', and '30.1'.
What I need to do is to populate an array (or any other better object) so that it duplicate each line; the array should have 3 elements per row. I must be having a brain-lock to not figure it out today. Here's my code:
string line;
int[] intArray;
intArray = new int[3];
int i = 0;
//Read Input file
using (StreamReader file = new StreamReader("Score_4.dat"))
{
while ((line = file.ReadLine()) != null && line.Length > 10)
{
line.Trim();
string[] parts;
parts = line.Split(' ');
intArray[0][i] = parts[0];//error: cannot apply indexing
i++;
}
}
Down the road in my code, I intend to make some API calls to a server by constructing a Json object while looping through the array (or alternate object).
Any idea?
Thanks
If you only need the data to be transferred to JSON then you don't need to process the values of the data, just reformat it to JSON arrays.
As you don't know the number of lines in the input file, it is easier to use a List<>, whose capacity expands automatically, to hold the data rather than an array, whose size you would need to know in advance.
I took your sample data and repeated it a few times into a text file and used this program:
static void Main(string[] args)
{
string src = #"C:\temp\Score_4.dat";
List<string> dataFromFile = new List<string>();
using (var sr = new StreamReader(src))
{
while (!sr.EndOfStream)
{
string thisLine = sr.ReadLine();
string[] parts = thisLine.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 3)
{
string jsonArray = "[" + string.Join(",", parts) + "]";
dataFromFile.Add(jsonArray);
}
else
{
/* the line did not have three entries */
/* Maybe keep a count of the lines processed to give an error message to the user */
}
}
}
/* Do something with the data... */
int totalEntries = dataFromFile.Count();
int maxBatchSize = 50;
int nBatches = (int)Math.Ceiling((double)totalEntries / maxBatchSize);
for(int i=0;i<nBatches;i+=1)
{
string thisBatchJsonArray = "{\"myData\":[" + string.Join(",", dataFromFile.Skip(i * maxBatchSize).Take(maxBatchSize)) + "]}";
Console.WriteLine(thisBatchJsonArray);
}
Console.ReadLine();
}
to get this output:
{"myData":[[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1]]}
{"myData":[[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1],[1,-88,30.1],[2,-89,30.1]]}
It should be easy to adjust the format as required.
I would create a custom Item class and then populate a list, for easy access and sorting, with self contained items. something like:
public Class MyItem
{
public int first { get; set; }
public int second { get; set; }
public float third { get; set; }
public MyItem(int one, int two, float three)
{
this.first = one;
this.second = two;
this.third = three;
}
}
then you could do:
List<MyItem> mylist = new List<MyItem>();
and then in your loop:
using (StreamReader file = new StreamReader("Score_4.dat"))
{
while ((line = file.ReadLine()) != null && line.Length > 10)
{
line.Trim();
string[] parts;
parts = line.Split(' ');
MyItem item = new Item(Int32.Parse(parts[0]),Int32.Parse(parts[1]),Float.Parse(parts[2]));
mylist.Add(item);
i++;
}
}
As there are numbers like 30.1 so int is not suitable for this, and also it must not be a double[] but double[][]:
string[] lines = File.ReadAllLines("file.txt");
double[][] array = lines.Select(x => s.Split(' ').Select(a => double.Parse(a)).ToArray()).ToArray();
Issue is that int array is single dimensional.
My suggestion is that you can put a class with 3 properties and populate a list of class there. It's better to have class with same property names that you require to build JSON. So that you can easily serialize this class to JSON using some nugets like Newtonsoft and make api calls easily.
Your int array is a single dimensional array yet you're trying to index it like a multidemensional array. It should be something like this:
intArray[i] = parts[0]
(However you'll need to handle converting to int for parts that are fractional)
Alternatively, if you want to use a multidimensional array, you have to declare one.
int[][] intArray = new int[*whatever your expected number of records are*][3]
Arrays have a static size. Since you're reading from a file and may not know how many records there are until your file finishes reading, I recommend using something like a List of Tuples or a Dictionary depending on your needs.
A dictionary will allow you to have quick lookup of your records without iterating over them by using a key value pair, so if you wanted your records to match up with their line numbers, you could do something like this:
Dictionary<int, int[]> test = new Dictionary<int, int[]>();
int lineCount = 1;
while ((line = file.ReadLine()) != null && line.Length > 10)
{
int[] intArray = new int[3];
line.Trim();
string[] parts = line.Split(' ');
for (int i = 0; i < 3; i++)
{
intArray[i] = int.Parse(parts[i]);
}
test[lineCount] = intArray;
lineCount++;
}
This will let you access your values by line count like so:
test[3] = *third line of file*

How to call function with List in head

I want to send along several integers with my function through a list like this:
public string createCompleteJump(List<int>kID)
kID is they key ID which is connected to several dictionaries hence why it is important to select different integers.
function:
public string createCompleteJump(List<int>kID)
{
// List<int> kID = new List<int>(); // Key ID
double vID = 3; // Value ID
string v2ID = "Framåt";
var myKey = qtyScrews[kID[0]].FirstOrDefault(y => y == vID);
var myKey2 = qtyFlips[kID[1]];
var myKey3 = jumpCombination[kID[2]].FirstOrDefault(y => y == v2ID);
var myKey4 = jumpHeight[kID[3]];
var myKey5 = startPos[kID[4]];
var str = $"{myKey}{myKey2}{myKey3}{myKey4}{myKey5}";
Console.Write("\nCompleteJump:" + str);
return str;
}
How would I send along 5 arguments when calling the function through a list?
Eg:
public string createCompleteJump(3,4,2,3,4)
You either need to create a list to pass as argument:
createCompleteJump(new List<int> {3,4,2,3,4});
or you could change your method to accept an undefined number of arguments:
public string createCompleteJump(params int[] kID)
{ /* ... */ }
The params key word states that there can be an arbitrary number of int and that they are combined into an array:
createCompleteJump(3,4,2,3,4);
results in an int[] array containing the specified values.
use params keyword:
public string createCompleteJump(params int[] kID)
https://msdn.microsoft.com/library/w5zay9db.aspx
You can use params or you can instantiate your list to be sent to your function, like this:
List<int> keyIDList = new List<int> {3,4,2,3,4};
createCompleteJump(keyIDList)

What is the easiest way to split columns from a txt file

I've been looking around a bit but haven't really found a good example with what I'm struggling right now.
I have a .txt file with a couple of columns as follows:
# ID,YYYYMMDD, COLD,WATER, OD, OP,
52,20120406, 112, 91, 20, 130,
53,20130601, 332, 11, 33, 120,
And I'm reading these from the file into a string[] array.
I'd like to split them into a list
for example
List results, and [0] index will be the first index of the columns
results[0].ID
results[0].COLD
etc..
Now I've been looking around, and came up with the "\\\s+" split
but I'm not sure how to go about it since each entry is under another one.
string[] lines = File.ReadAllLines(path);
List<Bus> results = new List<Bus>();
//Bus = class with all the vars in it
//such as Bus.ID, Bus.COLD, Bus.YYYYMMDD
foreach (line in lines) {
var val = line.Split("\\s+");
//not sure where to go from here
}
Would greatly appreciate any help!
Kind regards, Venomous.
I suggest using Linq, something like this:
List<Bus> results = File
.ReadLines(#"C:\MyFile.txt") // we have no need to read All lines in one go
.Skip(1) // skip file's title
.Select(line => line.Split(','))
.Select(items => new Bus( //TODO: check constructor's syntax
int.Parse(items[1]),
int.Parse(items[3]),
DateTime.ParseExact(items[2], "yyyyMMdd", CultureInfo.InvariantCulture)))
.ToList();
I would do
public class Foo
{
public int Id {get; set;}
public string Date {get; set;}
public double Cold {get; set;}
//...more
}
Then read the file
var l = new List<Foo>();
foreach (line in lines)
{
var sp = line.Split(',');
var foo = new Foo
{
Id = int.Parse(sp[0].Trim()),
Date = sp[1].Trim(),//or pharse the date to a date time struct
Cold = double.Parse(sp[2].Trim())
}
l.Add(foo);
}
//now l contains a list filled with Foo objects
I would probably keep a List of properties and use reflection to populate the object, something like this :
var columnMap = new[]{"ID","YYYYMMDD","COLD","WATER","OD","OP"};
var properties = columnMap.Select(typeof(Bus).GetProperty).ToList();
var resultList = new List<Bus>();
foreach(var line in lines)
{
var val = line.Split(',');
var adding = new Bus();
for(int i=0;i<val.Length;i++)
{
properties.ForEach(p=>p.SetValue(adding,val[i]));
}
resultList.Add(adding);
}
This is assuming that all of your properties are strings however
Something like this perhaps...
results.Add(new Bus
{
ID = val[0],
YYYYMMDD = val[1],
COLD = val[2],
WATER = val[3],
OD = val[4],
OP = val[5]
});
Keep in mind that all of the values in the val array are still strings at this point. If the properties of Bus are typed, you will need to parse them into the correct types e.g. assume ID is typed as an int...
ID = string.IsNullOrEmpty(val[0]) ? default(int) : int.Parse(val[0]),
Also, if the column headers are actually present in the file in the first line, you'll need to skip/disregard that line and process the rest.
Given that we have the Bus class with all the variables from your textfile:
class Bus
{
public int id;
public DateTime date;
public int cold;
public int water;
public int od;
public int op;
public Bus(int _id, DateTime _date, int _cold, int _water, int _od, int _op)
{
id = _id;
date = _date;
cold = _cold;
water = _water;
od = _od;
op = _op;
}
}
Then we can list them all in the results list like this:
List<Bus> results = new List<Bus>();
foreach (string line in File.ReadAllLines(path))
{
if (line.StartsWith("#"))
continue;
string[] parts = line.Replace(" ", "").Split(','); // Remove all spaces and split at commas
results.Add(new Bus(
int.Parse(parts[0]),
DateTime.ParseExact(parts[1], "yyyyMMdd", CultureInfo.InvariantCulture),
int.Parse(parts[2]),
int.Parse(parts[3]),
int.Parse(parts[4]),
int.Parse(parts[5])
));
}
And access the values as you wish:
results[0].id;
results[0].cold;
//etc.
I hope this helps.

Converting string array to double array

I have a file with alot of numbers, each index has 4 subnumbers
no1 no2 no3 no4
no1 no2 no3 no4
no1 no2 no3 no4
The file is a cvs file, but I need to read the numbers into an array as type double and make an interpolating, so I need to walkthrough the table.
Until now I have this, but I am stuck and do not really know how I nicely can convert the file to double values, so I can start calculate on them. Any suggestion ?
var filelines = from line in file.Skip(5)
select line.Split(';');
If you want a double[][], so one array per line:
double d;
double[][] lineValues = file.Skip(5)
.Select(l => l.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries))
.Where(arr => arr.Length == 4 && arr.All(s => double.TryParse(s, out d)))
.Select(arr => arr.Select(double.Parse).ToArray())
.ToArray();
You can split the line,parse each part into decimal and use SelectMany to flatten results:
file.Skip(5).SelectMany(line => line.Split(';').Select(decimal.Parse)).ToArray()
If there is certain values in each row, like let's say your cvs data store has a specific number of fields, s wiser and strongly typed move is to first make up a model for your data store, which according to the information you provided would be:
public class MyCVSModel {
public Double Number1 {get; set;}
public Double Number2 {get; set;}
public Double Number3 {get; set;}
public Double Number4 {get; set;}
}
Now, you can:
public static IEnumerable<MyCVSModel> Converion(String FileName){
var AllLines = System.IO.ReadAllLines(FileName);
foreach(var i in AllLines){
var Temp = i.Split('\t'); // Or any other delimiter
if (Temp.Lenght >= 4){ // 4 is because you have 4 values in a row
List<Double> TryConversion = new List<Double>();
foreach(var x in Temp) {
if (IsDouble(x))
TryConversion.Add(Convert.ToDouble(x));
else
TryConversion.Add(0);
}
MyCVSModel Model = new MyCVSModel();
Model.Number1 = TryConversion[0];
Model.Number2 = TryConversion[1];
Model.Number3 = TryConversion[2];
Model.Number4 = TryConversion[3];
yield return Model;
}
}
}
public static Boolean IsDouble(String Value) {
Regex R = new Regex(#"^[0-9]*(?:\.[0-9]*)?$");
return R.IsMatch(Value);
}

Categories