The following linq logic has 2 possible expressions that are based on the parameter values, I am looking for a way to combine the two expressions into a single expression, mainly so that I can declare and manage the join criteria once, rather than in 2 places.
- 1st scenario: Joins the Users and comments table based on project id and If parentId is null
- 2nd scenario: Joins the Users and comments table based on project id and parent id is not null
public Comment GetComments(int projectId, int parentId)
{
    List<Comment> comments= new List<Comment>();
    if(parentId==null)
    {
        comments = (from c in context.Comments
                    join users in context.Users
                    on c.CreatedBy equals users.Id
                    where c.ProjectId==projectId && c.ParentId==null
                    select new CommentModel
                    {
                        Id = c.Id,
                        Message = c.Message,
                        Date = c.Date,
                        UserName = users.UserName,
                        ProjectId=projectId,
                    }).ToList();
    }
    else
    {
        comments = (from c in context.Comments
                    join users in context.Users
                    on c.CreatedBy equals users.Id
                    where c.ProjectId==projectId && ParentId==c.parentId
                    select new CommentModel
                    {
                        Id = c.Id,
                        Message = c.Message,
                        Date = c.Date,
                        UserName = users.UserName,
                        ProjectId=projectId,
                    }).ToList();
    }
    
    return comments;
}
 
    