Sir Maxwell Sir Maxwell - 24 days ago 4
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
{
Verb,
Word,
Adjective
}

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
List<string>
to
IEnumerable<Token>
. How can I convert it?

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

Answer

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.

Comments