首页 > 解决方案 > 无法为列表赋值

问题描述

我正在使用 MVC 应用程序。这是我的模型。

public class Fruit
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public List<Colors> ColorsList { get; set; }

}

public class Colors
{
    public string ColorId { get; set; }
    public string ColorName { get; set; }
    public string ColorDescription { get; set; }
}

我在 Linq 中的查询:

var lstfruits = db.Fruits.Select(c => new Fruit {Id=c.Id, Name = c.Name, Description = c.Description });

foreach (var fruit in lstfruits)
{
    var lstColor = new List<Colors>();
    lstColor = db.Color.Where(f => f.FruitId == fruit.Id)
                       .Select(f => new Colors {ColorId=f.Id.ToString(), ColorName = f.Name, ColorDescription = f.Description })
                       .ToList();
    fruit.ColorsList = lstColor;
}

return lstfruits;

在查询后调试lstColoris not null 但lstfruits始终具有ColorsList = null所有元素的值。我错过了什么?

我知道我的查询工作正常,因为我确实从调试时的两个查询中获得了预期值。问题是将其分配给fruits.ColorsListfor 循环内部。

标签: c#asp.net-mvclinq

解决方案


将您的 foreach 转换为 For 循环。

for(int i=0;i<lstfruits.Count();i++)
{

    var lstColor = new List<Colors>();
    lstColor = db.Color.Where(f => f.FruitId == lstfruits[i].Id)
                       .Select(f => new Colors {ColorId=f.Id.ToString(), ColorName = f.Name, ColorDescription = f.Description })
                       .ToList();
    lstfruits[i].ColorsList = lstColor;
}

您实际上可以通过以下方式在循环中取消 List 初始化

for(int i=0;i<lstfruits.Count();i++)
{

    lstfruits[i].ColorsList = db.Color.Where(f => f.FruitId == lstfruits[i].Id)
                       .Select(f => new Colors {ColorId=f.Id.ToString(), ColorName = f.Name, ColorDescription = f.Description })
                       .ToList();

}

推荐阅读