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;
}