简体   繁体   English

为什么我只能在此IEnumerable <>中获得null

[英]why do I only get nulls in this IEnumerable<>

I'm trying to populate this IEnumerable with values from a db. 我试图用数据库中的值填充此IEnumerable。

I can't see what I'm doing wrong. 我看不到我在做什么错。

IEnumerable<Categories> categories = new List<Categories>();

List<SelectListItem> catItems = new List<SelectListItem>();

foreach (var cats in categories)
{
    catItems.Add(new SelectListItem
                     {
                         Text = cats.CategoryName,
                         Value = cats.CategoryID.ToString()
                     });
}

Here is the class: 这是课程:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace SportsStore.Domain.Entities
{
    public class Categories
    {
        [Key]
        public int CategoryID { get; set; }
        public string CategoryName { get; set; }
    }

}

您只需初始化一个新的类别集合,就不会添加任何类别。

How are you populating the categories list? 您如何填充类别列表? It won't just get filled by saying... 不仅仅是说...

IEnumerable<Categories> categories = new List<Categories>(); 

You need populate it somehow. 您需要以某种方式填充它。

Because here you create a new (and empty) list of Categories: 因为在这里您创建了一个新的(且为空)类别列表:

IEnumerable<Categories> categories = new List<Categories>();

and here you try to iterate over the empty list: 在这里,您尝试遍历空列表:

foreach (var cats in categories)
{

Which means you're never adding anything to cat.Items 这意味着您永远不会向cat.Items添加任何内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何告诉Resharper我的IEnumerable方法删除了空值? - How do I tell Resharper that my IEnumerable method removes nulls? 为什么.net中的数组只实现IEnumerable而不是IEnumerable <T>? - Why do arrays in .net only implement IEnumerable and not IEnumerable<T>? 我如何获得我的IEnumerable <T> IEnumerable上的扩展方法? - How do I get my IEnumerable<T> extension methods on an IEnumerable? 如何在视图中获取Ienumerable的属性? - How do I get property of an Ienumerable in the view? 为什么我得到“无法转换类型” IEnumerable <myType> &#39;到此LINQ查询上的&#39;myType&#39;? - Why do I get 'cannot convert type 'IEnumerable<myType>' to 'myType' on this LINQ query? 我如何获得DropDownListFor与IEnumerable一起使用 <SelectList> 一个cshtml页面? - How do i get a DropDownListFor to work with an IEnumerable<SelectList> with a cshtml page? 如何获取IEnumerable上通用参数的类型 <object> ? - How do I get the type of a generic parameter on IEnumerable<object>? 如何从.net中的IEnumerable <T>获取第一个元素? - How do I get the first element from an IEnumerable<T> in .net? 为什么我只得到“ .xlsx”而不是完整的串联字符串 - Why do I get only “.xlsx” instead of full concatenated string 为什么我只能从我的第一个 txt 中获得结果? - Why do I only get results from my first txt?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM