string categoryIDList = Convert.ToString(reader["categoryIDList"]);
if (!String.IsNullOrEmpty(categoryIDList))
{
c.CategoryIDList =
new List<int>().AddRange(
categoryIDList
.Split(',')
.Select(s => Convert.ToInt32(s)));
}
The class has a property IList CategoryIDList that I am trying to assign to above.
Error:
Error 1 Cannot implicitly convert type 'void' to 'System.Collections.Generic.IList'
Not sure what the issue is?
Your problem is that the AddRange method of the generic List class is declared as returning void.
Update: Edited to fix List<int>
vs. IList<int>
issue.
You need to change it to:
List<int> foo = new List<int>();
foo.AddRange(
categoryIDList
.Split(',')
.Select(s => Convert.ToInt32(s)));
c.CategoryIDList = foo;
Why not initialize the list with the results of your select query instead of doing AddRange since it takes IEnumerable as an overload:
c.CategoryIDList = new List<int>(categoryIDList.Split(',')
.Select(s => Convert.ToInt32(s)));
AddRange doesn't return a list - it returns void. You can do this via the constructor for List<T>
that takes an enumerable:
string categoryIDList = Convert.ToString(reader["categoryIDList"]);
if (!String.IsNullOrEmpty(categoryIDList))
{
c.CategoryIDList =
new List<int>(
categoryIDList.Split(',').Select(s => Convert.ToInt32(s))
);
}
To have better understanding of what is going on, I created example below.
Solution should be based on 1. list.AddRange, 2. then reassigning list to something else:
List<int> list1 = new List<int>{1,4, 8};
List<int> list2 = new List<int> { 9, 3, 1 };
//this will cause compiler error "AddRange cannot convert source type void to target type List<>"
//List<int> list3 = list1.AddRange(list2);
//do something like this:
List<int> list3 = new List<int>();
list3.AddRange(list1);
list3.AddRange(list2);
You're assigning the result of AddRange to c.CategoryIDList, not the new list itself.