无法从通用列表中获取值<t>

时间:2019-01-18 07:35:39

标签: c#

如何获取自定义类型的通用列表的第一个和最后一个元素。

嗨,我的代码中有这个通用列表

我想将已添加到列表week1中的值传递给一个函数,但是我什至无法打印出这些值,或者将其分配给另一个DateTime变量时都不能。

Response.Write(week1[0])这样的简单东西不起作用,我什至尝试了(week1.First()),但是foreach循环却像一个符咒。我不想要,实际上我只需要一周之间的第一个和最后一个日期。

List<Week> week1 = new List<Week>();
List<Week> week2 = new List<Week>();
List<Week> week3 = new List<Week>();
List<Week> week4 = new List<Week>();
List<Week> week5 = new List<Week>();

public class Week
{
    //this class has a default constructor
    public DateTime datefortheweek { get; set; }
}

//this works fine
foreach(Week text in week1)
{
    Response.Write(text.datefortheweek);
    Response.Write("<br/>");
}

2 个答案:

答案 0 :(得分:3)

Response.Write(week1[0])无法正常工作可能是因为Response.Write没有将Week作为参数。

如果仔细观察,您的foreach循环方法将使用text.datefortheweek而不是text。您还应该在datefortheweek之后访问week[0],它应该可以工作:

Response.Write(week1[0].datefortheweek);
Response.Write(week1[week1.Length - 1].datefortheweek);

我还建议您使用2D数组/列表存储Week。这样可以节省您编写week1week2week3 ... weekX的时间。

List<List<Week>> weeks = new List<List<Week>>();
weeks.Add(new List<Week>());
weeks.Add(new List<Week>());
weeks.Add(new List<Week>());
...

答案 1 :(得分:2)

您需要

Response.Write(week1[0].datefortheweek) 

Response.Write(week1.First().datefortheweek)