我为MVC应用程序创建了以下视图模型。我想做的是将它设为IEnumerable
类,以便我可以使用foreach
语句遍历页面中的数据。
public class EstimateDetailsModel
{
public string dma { get; set; }
public string callsign { get; set; }
public string description { get; set; }
}
如果它是相关的,这里是我的存储库中相应的Linq查询,它实例化EstimatesDetailsModel
类:
public IEnumerable<EstimateDetailsModel> GetEstimateDetails(int id)
{
var estimateDetails = from e in db.Estimates
join es in db.EstimateStations on e.EstimateID equals es.EstimateID
join s in db.Stations on es.StationID equals s.StationID
join m in db.Markets on s.MarketID equals m.MarketID
where e.EstimateID == 1
select new EstimateDetailsModel { dma = m.DmaName, callsign = s.CallSign, description = s.StationDescription };
return estimateDetails;
}
答案 0 :(得分:15)
也许你正在寻找这样的东西:
public class EstimateDetailsModel : IEnumerable<string>
{
public string Dma { get; set; }
public string Callsign { get; set; }
public string Description { get; set; }
public IEnumerator<string> GetEnumerator()
{
yield return Dma;
yield return Callsign;
yield return Description;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
(我将属性大写,这是正常的风格。)
答案 1 :(得分:0)
听起来你可能会尝试这样做吗?
public class EstimateDetailsModel: List<EstimateDetailsModel.EstimateDetail>
{
public class EstimateDetail
{
public string dma { get; set; }
public string callsign { get; set; }
public string description { get; set; }
}
}
答案 2 :(得分:0)
为什么不在EstimateDetailsModel中使用一个从存储库中公开EstimateDetails的属性?这样的事情,假设你在模型中有一个Repository引用:
public class EstimateDetailsModel
{
public int EstimateID { get; set; }
public IEnumerable<EstimateDetailsModel> EstimateDetails
{
return Repository.GetEstimateDetails(this.EstimateID);
}
}
答案 3 :(得分:0)
通过反射,可以自动枚举任何对象的属性名称和值(请参阅this question中的others)。但它有时有点矫枉过正。我假设你有兴趣查看EstimateDetailsModel
作为字典。我建议如下:
public class EstimateDetailsModel : IEnumerable<KeyValuePair<string, string>>
{
public string Dma { get; set; }
public string CallSign { get; set; }
public string Description { get; set; }
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
yield return new KeyValuePair<string, string>("Dma", Dma);
yield return new KeyValuePair<string, string>("CallSign", CallSign);
yield return new KeyValuePair<string, string>("Description", Description);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}