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?
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>
.
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With