Sir Maxwell Sir Maxwell - 1 year ago 63
C# Question

Convert a list of IEnumerable<foo> to List<string>

I'm trying to convert my List of Token to a List of string.

Here's my class Token:

internal class Token
private TokenType Type { get; set; }
private string Value { get; set; }
private int Index { get; set; }

public enum TokenType

public IEnumerable<Token> Tokenizer(string source)
var token = source.Split().ToList();
return token;

What I wanna do is split the source string into a List of string and then use that List to do other cool things for my parser...
When I add this line of code, it tells me "Cannot convert from a
. How can I convert it?

var token = source.Split().ToList();

Answer Source

The error message means exactly what it says.

public IEnumerable<Token> Tokenizer(string source)

returns type IEnumerable<Token>, but

var token = source.Split().ToList();

is of type List<string>. There's no conversion between List<string> and List<Token> (or, for that matter, between string and Token).

You need to do something like:

var token = source.Split().Select(item => new Token(item)).ToList();

You'll also need to write a constructor that takes type string and initializes the Token with it.

You might also consider making the Tokenizer method static so that you don't need to have an existing Token instance to use it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download