0

What I am trying to do is convert a string to a List of strings using linq. I try the following line of code:

value = "one,two,three,four";

List<string> arr = value.Split(',').Select(s => s.ToList());

But I am getting the error:

Error 1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable>' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)

If anyone could provide some help that would be awesome.

1

8 Answers 8

10

Hello you can try with

 value.Split(',').ToList();
Sign up to request clarification or add additional context in comments.

Comments

3

You've got the ToList on each individual array element - i.e. on each string. That call itself is valid because string implements IEnumerable<char>, but it means you're creating an IEnumerable<List<char>> which isn't what you want.

I don't think you need the Select at all - just use:

List<string> arr = value.Split(',').ToList();

Comments

2

One of the list constructors takes an enumerable:

var arr = new List<string>(value.Split(','));

Not sure why people insist on linq extensions for everything...

2 Comments

I guess it's a matter of taste, but I find the LINQ version more readable (no angle brackets, no nested regular brackets).
@jeroenh Undoubtedly, and likely the extension method implementation uses this constructor anyway. I just find it funny how many things are styled like linq extensions these days :-) I'd use either without a second thought, which for me is most important as spending a second thought on it is a little bit of a waste.
1
value = "one,two,three,four";

List<string> arr = value.Split(',').Select(s => s).ToList();

or simpler:

List<string> arr = value.Split(',').ToList();

Comments

1

Even though you don't need select, but still if you want to use it then it should be:

  List<string> arr = value.Split(',').Select(s => s).ToList();

Or you can simply do :

  List<string> arr = value.Split(',').ToList();

1 Comment

+1 showing the version with Select, even if it's not needed. It lets the OP compare to see what they did wrong.
0

You shouldn't need the Select:

value = "one,two,three,four";

List<string> arr = value.Split(',').ToList();

Comments

0
string value = "one,two,three,four";
List<string> arr = value.Split(',').ToList();

Comments

0

You don't need to use LINQ here, instead you can simply do this:

string value = "one,two,three,four";
List<string> arr = value.Split(',').ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.