-2

I have:

IEnumerable<string> c = codigo_incidencia.Split('#');

I need to cast "c" to be an IEnumerable<int>. I don´t know how to do this cast in C#.

Can someone help me?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    Have you tried anything? – Gilad Green Nov 02 '17 at 14:58
  • I wouldn't *cast* this, I'd more likely call `.Select()` on the returned value of `.Split()` and parse the string within the `.Select()`. – David Nov 02 '17 at 14:59
  • That's not a cast but a conversion. Of course this could happen only if your IEnumerable could be converted to an IEnumerable. What is the content of _codigo_incidencia_? – Steve Nov 02 '17 at 15:00
  • 1
    kudos to @ChristianGollhardt for finding an appropriate duplicate. FGITW who posted answers are not so fast; they should have use close-votes (or even dupehammer), but noooo – ASh Nov 02 '17 at 15:20

3 Answers3

8

Shortest way is to using linq .Select likewise:

var c = codigo_incidencia.Split('#').Select(int.Parse);

If you are not sure that the sections are valid ints then you'd want to use a TryParse as in: Select parsed int, if string was parseable to int. And if working with C# 7.0 you can look at this answer of the question:

var result = codigo_incidencia.Split('#')
                 .Select(s => new { Success = int.TryParse(s, out var value), value })
                 .Where(pair => pair.Success)
                 .Select(pair => pair.value);
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
6

Use LINQ:

IEnumerable<int> c = codigo_incidencia.Split('#').Select(x => int.Parse(x));
adjan
  • 13,371
  • 2
  • 31
  • 48
2

You can do it like this if the strings are always guaranteed to be numbers:

IEnumerable<int> c = codigo_incidencia.Split('#').Select(stringValue => int.Parse(stringValue));
David Watts
  • 2,249
  • 22
  • 33