Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'string' to 'System.Collections.Generic.List<string>'

Tags:

string

c#

list

This question has probably been answered hundreds of times, but here goes.

I have this chunck of code:

private void PopulateStringDropdownList(List<ObjectInfo> listObject,
                                        object selectedType = null)
{
    List<string> listString = listObject.OrderBy(x => x.m_Type).ToString();
    for (int i = 0; i < listString .Count; i++)
    {
        for (int j = i + 1; j < listString .Count; j++)
        { 
            if (String.Equals(listString [i], listString [j]))
            {
                listString.RemoveAt(j);
            }
        }
    }
    ViewBag.property1 = new SelectList(listString );
}

So basically I'm trying to populate a dropdown List with strings coming from a property of each objects contained in the list I pass in parameter.

But the code doesn't compile because of the error you're seeing up there, and I've yet to understand why exactly. Any help anyone?

like image 215
hsim Avatar asked Feb 01 '13 20:02

hsim


3 Answers

This is the problematic line:

List<string> listString = listObject.OrderBy(x => x.m_Type).ToString();

ToString returns a string, and you're trying to assign to a List<string> variable.

You need to do something like this:

List<string> listString = listObject.OrderBy(x => x.m_Type)
                                    .Select(x => x.ToString())
                                    .ToList();

This statement will order your listObject enumerable to the order that your want, then convert the values to strings, and finally convert the enumerable to a List<string>.

like image 133
FishBasketGordo Avatar answered Nov 04 '22 21:11

FishBasketGordo


Look at this code:

List<string> listString = listObject.OrderBy(x => x.m_Type).ToString();

The right hand side expression is calling ToString() on the result of OrderBy - which isn't useful itself, and will result in a string.

You're then trying to assign that string expression to a new variable of type List<string>. That's not going to work.

I suspect you just want ToList instead of ToString:

List<string> listString = listObject.OrderBy(x => x.m_Type).ToList();
like image 5
Jon Skeet Avatar answered Nov 04 '22 22:11

Jon Skeet


I think you want ToList instead of ToString.

Also, if all you're trying to do is remove duplicates, you can simply use LINQ and do this:

List<string> listString = listObject.OrderBy(x => x.m_Type).
    Select(x => x.ToString()).Distinct().ToList();
like image 2
Matthew Strawbridge Avatar answered Nov 04 '22 21:11

Matthew Strawbridge