How to handle exception raised in linq

后端 未结 2 685
太阳男子
太阳男子 2021-01-20 12:49

gyus! Suppose I have such simple LINQ expression

IEnumerable res =
    from rqResult in MatchesList
    select new StopListMat         


        
2条回答
  •  萌比男神i
    2021-01-20 13:33

    Because of deferred execution the query is not executed until you evaluate the query, such as by making use of the .ToList() method. The exception will be thrown at that time only.

    To avoid the problem you need to modify the query. something as below

    IEnumerable res =
        from rqResult in MatchesList
        select new StopListMatchViewModel
        {
            MatchDate = DateTime.ParseExact(
                ((rqResult.Row["MatchDate"]==null) ?
                    rqResult.Row["MatchDate"] : DateTime.MinValue).ToString(), "dd.MM.yyyy HH:m:ss", fmtInfo),
            Remark = rqResult.Row["Remark"].ToString()
        }
    

    Note : DateTime.MinValue is used when the value of rqResult.Row["MatchDate"] is null which used to avoid null

提交回复
热议问题