简体   繁体   中英

How can I convert comma separated string into a List<int>

string tags = "9,3,12,43,2"

List<int> TagIds = tags.Split(',');

This doesn't work cause the split method returns a string[]

这是一种方法:

List<int> TagIds = tags.Split(',').Select(int.Parse).ToList();

If you want to include some simple validation and skip over invalid values (instead of throwing an exception), here's something that uses TryParse:

string csv = "1,2,3,4,a,5";
int mos = 0;
var intList = csv.Split(',')
                    .Select(m => { int.TryParse(m, out mos); return mos; })
                    .Where(m => m != 0)
                    .ToList();

//returns a list with integers: 1, 2, 3, 4, 5

EDIT: Here is an updated query based on feedback by Antoine. It calls TryParse first to filter out any bad values, and then Parse to do the actual conversion.

string csv = "1,2,3,4,a,5,0,3,r,5";
int mos = 0;
var intList = csv.Split(',')
                    .Where(m => int.TryParse(m, out mos))
                    .Select(m => int.Parse(m))
                    .ToList();

//returns a list with integers: 1, 2, 3, 4, 5, 0, 3, 5

Edit 2: An updated query for C# 7.0, thanks to feedback from Charles Burns. Note that we get rid of the extra mos variable with this approach, so it's a bit cleaner.

string csv = "1,2,3,4,a,5,0,3,r,5";
var intList = csv.Split(',')
                 .Where(m => int.TryParse(m, out _))
                 .Select(m => int.Parse(m))
                 .ToList();

您可以使用带有int.Parse() LINQ 将string[]转换为IEnumerable<int> ,然后将该结果传递给List<T>构造函数:

var tagIds = new List<int>(tags.Split(',').Select(s => int.Parse(s)));

A little LINQ goes a long way:

 List<int> TagIds = tags.Split(',')
         .Select(t => int.Parse(t))
         .ToList();

Without LINQ Query , you can choose this method ,

string tags = "9,3,12,43,2";
List<string> numbers = nos.Split(',').ToList<string>();

and then you can convert this List into integer type...

string tags = "9,3,12,43,2"

List<int> TagIds = tags.Split(',').Select(x => x.Trim()).Select(x=> Int32.Parse(x)).ToList();

If you are using C# 3.5 you can use Linq to achieve this

string tags = "9,3,12,43,2";
List<int> tagIds = tags.Split(',').Select(s=>int.Parse(s)).ToList();

or the short one

string tags = "9,3,12,43,2";
List<int> tagIds = tags.Split(',').Select(int.Parse).ToList();
string tags = "9,3,12,43,2";
List<int> TagIds = tags.Split(',').Select(int.Parse).ToList();

I made a modification to khalid13's answer. If the user put a string of "0", his answer would remove that from the resulting list. I did something similar but used an anonymous object.

var result = commaSeparatedString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(s => new { didConvert = int.TryParse(s.TrimNullProtection(), out convertedInt), convertedValue = convertedInt })
            .Where(w => w.didConvert)
            .Select(s => s.convertedValue)
            .ToList();

TrimNullProtection is a custom function I made that protects if the string is null.

What the above does is strip out any strings that were not able to be converted with no error. If you need to error if there was a problem with the conversion, then the accepted answer should do the trick.

I stumbled upon this and I just want to share my own solution without linq. This is a primitive approach. Non-integer values will not be added in the list also.

List<int> TagIds = new List<int>();
string[] split = tags.Split(',');
foreach (string item in split)
{
    int val = 0;
    if (int.TryParse(item, out val) == true)
    {
        TagIds.Add(val);
    }
}

Hope this helps.

Using java 8 stream,

  List<Integer> valueInInt1 = Arrays.stream(tags.split(",")).mapToInt(num -> Integer.parseInt(num)).boxed().collect(Collectors.toList());

  List<Integer> valueInInt2 = Arrays.stream(tags.split(",")).map(num -> Integer.parseInt(num)).collect(Collectors.toList());

I always prefer java 8 stream as you can always use parallel stream . So, if you have thousands/ millions of record. It'll be fast.

It's simple. First split the string. Trim blank space present after comma(,). Then use system defined ToList()

string inputText = "text1, text2"

To remove the space after ',' and convert this comma separated text to List

List<string> resultList = (inputText.Split(',')).Select(t => t).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM