【问题标题】:Exception in traversal of Anonymous typed list in ASP.netASP.net 中匿名类型列表遍历异常
【发布时间】:2014-04-08 13:06:43
【问题描述】:

我在 ASP.Net 中为Repeater 使用匿名类型列表,但问题是如果在整个列表中存在任何空值或缺少属性的对象,它不会处理下一个元素,只会给我异常。我想要的是,如果我的整个列表中的任何元素具有空值或缺失值,则应该简单地跳过它。就像我们使用 foreach 循环一样,我们可以检查对象,或者我们可以应用 try catch 来防止异常。是否有某种匿名类型列表及其遍历的方法。

这是我的匿名类型列表。

 var newList = li.Select(p => new
            {
                p.Id,
                Title = new util.AlertMaker().GetOfferHyperLink(p.Id, p.Text, true),
                Status = new util.StatusCompiler().CompileStatus(Numerics.GetInt(p.Status)),
                UserName=p.Member.UserName+"",
                DateTimeTitle = Convert.ToDateTime(p.Date).ToString(),

            });

【问题讨论】:

    标签: asp.net .net repeater anonymous-types


    【解决方案1】:

    您可以使用这种方法。我已经编辑了 UserNameDateTimeTitle 属性的代码。

       var newList = li.Select(p => new
                    {
                        p.Id,
                        Title = new util.AlertMaker().GetOfferHyperLink(p.Id, p.Text, true),
                        Status = new util.StatusCompiler().CompileStatus(Numerics.GetInt(p.Status)),
                        UserName=p.Member.UserName==null?string.empty: p.Member.UserName+" ",
                        DateTimeTitle =p.Date==null?string.Empty: Convert.ToDateTime(p.Date).ToString(),
    
                    });
    

    【讨论】:

    • 是 UserName=p.Member==null?string.empty: p.Member.UserName+" ",
    【解决方案2】:

    我可以看到你的列表抛出异常的唯一原因——简单地通过迭代——是如果你调用的方法(GetOfferHyperLink()、Numerics.GetInt() 等)不能处理传入的空值.

    修复这些之后,我会像这样编写你的方法:

        var newList = li.Select(p => new
            {
                p.Id,
                Title = new util.AlertMaker().GetOfferHyperLink(p.Id, p.Text, true),
                Status = new util.StatusCompiler().CompileStatus(Numerics.GetInt(p.Status)),
                UserName=p.Member.UserName+"",
                DateTimeTitle = Convert.ToDateTime(p.Date).ToString()
            }).Where(x => !String.IsNullOrEmpty(x.Title) 
                       && !String.IsNullOrEmpty(x.Status)
                       && !String.IsNullOrEmpty(x.UserName) 
                       && !String.IsNullOrEmpty(x.DateTimeTitle));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多