-3

I have a self referencing object, which I need to converted from one to another object which is similar. I'm unable to find suitable method to do the convert with recursion without leading into an infinite loop. Any help would be appreciated.Still learning my ropes in c#

Object 1:

public class Comment
{
    public string User{ get; set; }
    public List<Comment> Replies { get; set; }
}

Object 2:

public class CommentRepo
{
    public string User{ get; set; }
    public ICollection<CommentRepo> Replies { get; set; }
}

I set my object as follows:

  var comment = new Shared.Models.Comment
        {
            User = "Test User"
        };


        var reply1 = new Shared.Models.Comment
        {
            User = "Reply User 1"
        };

        var subreply1 = new Shared.Models.Comment
        {

            User = "Sub Reply User 1"
        };

        var sublist = new List<Shared.Models.Comment>() { subreply1 };

        reply1.Replies = sublist;

        var reply2 = new Shared.Models.Comment
        {
            User = "Reply User 2"
        };

        var listed = new List<Shared.Models.Comment>() {reply1, reply2};


        comment.Replies = listed;

Method to convert: Here is where I run out of steam.

    public ICollection<CommentRepo> ToCommentRepo(IEnumerable<Shared.Models.Comment> comments)
    {
        if (comments == null) return null;

        var commentRepo = comments.Select(entity => new CommentRepo
        {
            User = entity.User,
            Replies = entity.Replies.Count > 0 ? ToCommentRepo(entity.Replies) : null,
        }).ToList();

        return commentRepo;
    }
  • What exactly does "running out of steam" mean here? If you have a working ToCommentRepo() it ought to work. – H H Jun 07 '15 at 10:57
  • It does not look like you have any circular references in your example, so you aren't supposed to get an infinine loop, unless you have item(s) in the Replies collection that contain the original comment, but that should not be the case, right? – Denis Yarkovoy Jun 07 '15 at 11:01
  • @ Denis Yarkovoy, Oops your right. I had a few circular references, which blew up.Thanks for your help and time. – user2368215 Jun 07 '15 at 13:59
  • Sure, you are welcome. Kindly accept my answer if you believe that it helped you to solve your problem, thanks – Denis Yarkovoy Jun 07 '15 at 14:03

1 Answers1

1

The code in the original question should not lead to infinite loop if I understand the user2368215's logic correctly. However, if the circular references are possible, there is a simple way to detect and avoid infinite loops by declaring the Dictionary outside the ToCommentRepo(...) and add new mapping from Comment to CommentRepo to this dictionary each time new CommentRepo object is created. Then, at the beginning of the ToCommentRepo(...) method simply check if the mapping already exists and return it, instead of calling LINQ method to create new mapping.

Denis Yarkovoy
  • 1,277
  • 8
  • 16