2

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);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Mehmet Yüce
  • 59
  • 1
  • 10

3 Answers3

2

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);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
2

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();
CSharpie
  • 9,195
  • 4
  • 44
  • 71
0

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

Community
  • 1
  • 1
Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115