The following code works good
IEnumerable<GroupedSelectListItem> groupList = db.Categories.Select(p => new GroupedSelectListItem()
{
GroupKey = p.ParentCategory.Name,
GroupName = p.ParentCategory.Name,
Text = p.Name,
Value = p.Name
});
While the below code generates object reference not set to an instance error
List<Category> orderedList = new List<Category>();
var rootList = db.Categories.Where(c => c.ParentCategoryId == null).ToList();
foreach (var item in rootList)
{
orderedList.Add(item);
if (item.SubCategories.Count != 0)
{
foreach (var subcat in item.SubCategories)
{
orderedList.Add(subcat);
if (subcat.SubCategories.Count != 0)
{
foreach (var subsubcat in subcat.SubCategories)
{
orderedList.Add(subsubcat);
}
}
}
}
}
IEnumerable<GroupedSelectListItem> groupList = orderedList.Select(p => new GroupedSelectListItem()
{
GroupKey = p.ParentCategory.Name,
GroupName = p.ParentCategory.Name,
Text = p.Name,
Value = p.Name
});
Error Detail
Line 54: IEnumerable groupList = orderedList.Select(p => new GroupedSelectListItem()
NOTE: The table for Categories in database contains element with ParentCategoryId for some records equal to null
The first code snippet is using Linq-to-entities with automatic coalescence. It menas that if p doesn’t have
ParentCategoryit will work without problem on SQL level. The second example use Linq-to-objects where no such feature exists. You must manually check ifParentCategoryproperty is filled prior to accessing its properites: