How to select specific fields from database using LINQ to SQL

I’m working on an ASP.NET MVC application and need help with LINQ to SQL queries. I want to fetch multiple database columns but I’m having trouble with the output format.

Here’s my repository method:

public IEnumerable<string> fetchUserFeedback(int ticketNumber)
{
    var feedback = from f in _dataContext.Feedback
                   where f.TicketNumber == ticketNumber
                   select new { f.UserID, f.Message, f.CreatedDate }.ToString();
    
    return feedback;
}

And my controller action:

public string LoadFeedback(string ticketId)
{
    List<string> results = _feedbackService.fetchUserFeedback(Convert.ToInt32(ticketId)).ToList();
    string output = null;
    foreach (string record in results)
    {
        output += record + "\n";
    }
    return output;
}

The JavaScript part:

$("#loadBtn").click(function () {
    var requestData = {
        ticketId: $("#ticketNumber").val(),
        message: $("#userInput").val(),
        userId: $("#currentUser").val()
    };
    
    $.ajax({
        type: "POST",
        url: "/Feedback/SaveFeedback",
        data: requestData,
        success: function (response) {
            $.ajax({
                type: "GET",
                url: "/Feedback/LoadFeedback",
                data: { ticketId: $("#ticketNumber").val() },
                success: function (data) {
                    $("#feedbackContainer").html(data);
                }
            });
        }
    });
});

The current output shows: { UserID = 5, Message = hello, CreatedDate = 2/15/2024 10:30:00 AM }

I need clean output without the property names and braces, just the values like: 5 hello 2/15/2024. How can I format this properly?

Interesting approach! Are you trying to concat everythng into one string? Skip the .ToString() on the anonymous object and try select f.UserID + " " + f.Message + " " + f.CreatedDate.ToString() instead. Why do you need strings tho? Wouldn’t a custom class work better here?

You’re using anonymous objects wrong. Try select f.UserID.ToString() + " " + f.Message + " " + f.CreatedDate.ToString() in your LINQ query instead. That’ll give you the concatenated values without all the property names and bracket mess.

You’re getting that output because you’re calling ToString() on an anonymous object. Quick fix: use string interpolation instead of concatenation - select $"{f.UserID} {f.Message} {f.CreatedDate}". But honestly, don’t concatenate strings in your LINQ query at all. Return IEnumerable<Feedback> or a custom DTO from your repository, then format the data in your controller or view. Way cleaner separation of concerns and easier to maintain. In your controller, just use string.Join(" ", record.UserID, record.Message, record.CreatedDate) when you need the formatted string.