c# - 无法为列表赋值
问题描述
我正在使用 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;
在查询后调试lstColor
is not null 但lstfruits
始终具有ColorsList = null
所有元素的值。我错过了什么?
我知道我的查询工作正常,因为我确实从调试时的两个查询中获得了预期值。问题是将其分配给fruits.ColorsList
for 循环内部。
解决方案
将您的 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();
}
推荐阅读
- git - 错误“远程:错误:GH007”即使我使用相同的用户名和电子邮件
- excel - 在 Excel 中打开的工作簿上强制刷新/加载命名范围
- c# - 将一个文本文件中的字符串行与另一个文本文件进行比较,并在发生不匹配时显示错误
- javascript - 如果一个函数不使用等待,它是否应该是异步的
- objective-c - 带有 NSFetchedResultsController 的 UICollectionViewController 坏了,当更新所有对象的属性时,如果控制器按此属性排序
- django - 如何将数据从 get_avatar()(Google 登录)发送到我的模板?
- python - 使用 python PIL 调整文件夹中的图像大小
- python - 编写返回列表中最短单词的函数
- sass - 为什么 `gulp-sass` 看不到我的 `mixins.scss` 文件?
- javascript - 未捕获的语法错误:意外的标记“?”