1

I'm converting old code to use LINQ. The old code looked like this:

// Get Courses
sqlQuery = @"SELECT Comment.Comment, Status.StatusId, Comment.DiscussionBoardId, DiscussionBoard.CourseId, Comment.CommentID
            FROM Status INNER JOIN Comment ON Status.StatusId = Comment.StatusId INNER JOIN
                DiscussionBoard ON Comment.DiscussionBoardId = DiscussionBoard.DiscussionBoardId
            WHERE  (DiscussionBoard.CourseID = 'CourseID')";

var comments = new List<Comment>(dataContext.ExecuteQuery<Comment>(sqlQuery));

I've converted the above SQL to LINQ:

var db = new CMSDataContext();
var query = from c in db.Comments
                join s in db.Status on c.StatusId equals s.StatusId
                join d in db.DiscussionBoards on c.DiscussionBoardId equals d.DiscussionBoardId
                where d.CourseId == "CourseID"
                select new      
                {
                    d.ItemType,
                    c.Comment1,
                    s.Status1,
                    c.DiscussionBoardId,
                    d.CourseId,
                    c.CommentID
                };

The problem I've having, though, is with trying to get the results of the query into the List. Can someone offer me some pointers?

Thanks!

0

5 Answers 5

4

Try adding the ToList() method at the end of the query.

Sign up to request clarification or add additional context in comments.

Comments

2

Enclose the whole query in parentheses and add .ToList() at the end.

Or add another line:

var list = query.ToList();

1 Comment

Awesome! That worked perfectly! I had no idea about the ToList method (I'm just now learning LINQ). Thanks so much! As soon as timer is up, I'll mark answer.
2

How about the ToList method: query.ToList() ?

Comments

1

You'll need to do two things.

First, change your select to create a new instance of Comment instead of an anonymous type.

Second, either wrap the whole query in a call to ToList() or store the results in a temporary variable and call ToList() on that variable to get the List<Comment> as a result.

Comments

1

Either (A) wrap the entire call with Enumerable.ToList(<your query>), (B) surround the entire query with parentheses and call the ToList extension method at the end, or (C) call query.ToList() as a separate statement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.