2

Below is my string.

var str = "1,2,3,4,5";

var strArr = str.split(","); // this gives me an array of type string

List<int> intCol = new List<int>(); //I want integer collection. Like

What I am doing is:-

foreach(var v in strArr)
{
     intCol.add(Convert.ToInt(v));
}

Is it right way to do it?

Kgn-web
  • 7,047
  • 24
  • 95
  • 161
  • @sakbari: That duplicate isn't very close, it's not about a `,` separated list. – H H Jan 22 '17 at 09:48

2 Answers2

4

Well that's a way of doing it, certainly - but LINQ makes it a lot easier, as this is precisely the kind of thing it's designed for. You want a pipeline that:

  • Splits the original string into substrings
  • Converts each string into an integer
  • Converts the resulting sequence into a list

That's simple:

List<int> integers = bigString.Split(',').Select(int.Parse).ToList();

The use of int.Parse as a method group is clean here, but if you're more comfortable with using lambda expressions, you can use

List<int> integers = bigString.Split(',').Select(s => int.Parse(s)).ToList();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3
var numbers = str.Split(',').Select(x => int.Parse(x)).ToList();

But in such cases I would add some error handling in case the item could not be converted to an integer like this:

var strArr = str.Split(',')
    .Select(x =>
    {
        int num;
        if (int.TryParse(x, out num))
        {
            return num;
        }

        // Parse failed so return -1 or some other value or log it
        // or throw exception but then this whole operation will fail
        // so it is upto you and your needs to decide what to do in such
        // a case.
        return -1; 
    });

Note: Convert.ToInt() will throw a FormatException if the value cannot be converted. TryParse will not.

CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
  • Got your point. The thing is you are using FluentApi but indirectly you are doing the same what I was doing using the foreach loop. Right?? – Kgn-web Jan 22 '17 at 09:36