Kevin
Kevin

Reputation: 4848

Getting LINQ query result into a list?

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!

Upvotes: 1

Views: 617

Answers (5)

Timothy Shields
Timothy Shields

Reputation: 79441

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.

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245399

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.

Upvotes: 1

Yaakov Ellis
Yaakov Ellis

Reputation: 41480

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

Or add another line:

var list = query.ToList();

Upvotes: 2

We Are All Monica
We Are All Monica

Reputation: 13336

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

Upvotes: 2

myermian
myermian

Reputation: 32505

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

Upvotes: 4

Related Questions