Question

I am using Anonymous Typed List for Repeater in ASP.Net, but the problem is if in whole list there is any null or object with missing attributes, it does not process the next elements but just gives me exception. What i want is if any element in my whole list is having null value or missing value, it should be skipped simply. Just like if we use foreach loop we can check the objects or we can apply try catch to prevent exceptions. Is there some way for anonymous typed listing and their traversal.

Here is my anonymous typed list.

 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(),

            });
Was it helpful?

Solution

You can use this approach. I have edited your code for UserName and DateTimeTitle property.

   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(),

                });

OTHER TIPS

The only reason I can see for your list to throw exceptions -- simply by iterating -- is if the methods you call (GetOfferHyperLink(), Numerics.GetInt(), etc) can't handle null values being passed in.

After fixing those, I would write your method like so:

    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));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top