使用类中的数据填充List

时间:2017-07-17 12:40:21

标签: c#

你好我有这个带List的课程

public class Challenge
{
    public string ChallengeID { get; set; }
    public string ChallengeDate { get; set; }
    public string ChallengeName { get; set; }
    public string ChallengeIcon { get; set; }
    public string BetID { get; set; }
    public List<ChallengeItem> challengeItem { get; set; }
}

和List的另一个类

public class ChallengeItem
{
    public string CallengeItemID { get; set; }
    public string ChallengeID { get; set; }
    public string MatchID { get; set; }
    public string TeamAName { get; set; }
    public string TeamBName { get; set; }
    public string TeamAScore { get; set; }
    public string TeamBScore { get; set; }
    public string MatchDate { get; set; }
    public string Venue { get; set; }
    public string VenueCity { get; set; }
    public string MatchTime { get; set; }
    public string TeamAValue { get; set; }
    public string DrawValue { get; set; }
    public string TeamBValue { get; set; }
}

我正在尝试用数据填充类和列表。这个班级运作良好但列表不起作用。我得到&#34;对象参考未设置....&#34;。我的代码出了什么问题?

DateTime cha = Convert.ToDateTime("18.07.2017");
List<Challenge> challengesList = new List<Challenge>();
DataClassesDataContext db = new DataClassesDataContext();
var loadAllChallenges = (from challenge in db.Challenges
                             where Convert.ToDateTime(challenge.ChallengeDate).Date == cha.Date
                             select challenge).ToList();

foreach (var item in loadAllChallenges)
{
    DateTime today = Convert.ToDateTime(item.ChallengeDate);
    Challenge challenger = new Challenge();
    challenger.BetID = item.betID.ToString();
    challenger.ChallengeDate = today.ToShortDateString();
    challenger.ChallengeIcon = item.ChallengeIcon;
    challenger.ChallengeID = item.ChallengeID.ToString();
    challenger.ChallengeName = item.ChallengeName;
    challengesList.Add(challenger);
    foreach (var chall in challengesList)
    {
        Int64 id = Convert.ToInt64(item.ChallengeID);
        var loadItem = (from itemitem in db.raptor_Challenge_Items
                        where itemitem.ChallengeID == id
                        select itemitem).ToList().FirstOrDefault();
        ChallengeItem cItem = new ChallengeItem();
        cItem.MatchID = loadItem.MatchID.ToString();
        cItem.ChallengeID = loadItem.ChallengeID.ToString();
        cItem.CallengeItemID = loadItem.CallengeItemID.ToString();
        challenger.challengeItem.Add(cItem);
    }            
}

string JsonSerializeResults = JsonConvert.SerializeObject(challengesList);
string JsonStr = JsonSerializeResults;
context.Response.Write(JsonStr);

0 个答案:

没有答案