NealR
NealR

Reputation: 10669

Returning Linq query results into a List object (based on condition)

I need to return a number of Linq query results into a List object based on a foreign key value. What is the syntax for doing this? I am new to using Linq, so below is my best guess so far. I receive an error in the .Where() "clause" stating "The name 'pt' does not exist in the current context. Any help would be greatly appreciated!

        List<AgentProductTraining> productTraining = new List<AgentProductTraining>();

        var prodCodes = productTraining.Select(pt => new[]
                                                         {
                                                             pt.ProductCode,
                                                             pt.NoteId,
                                                             pt.ControlId
                                                         })
                                                         .Where(pt.CourseCode == course.CourseCode);

Upvotes: 0

Views: 1276

Answers (1)

Corey Adler
Corey Adler

Reputation: 16137

You would need to switch the locations of where and select if you're using extension methods:

var prodCodes = productTraining.Where(pt => pt.CourseCode == course.CourseCode)
                               .Select(pt => new SomeRandomType
                                                         {
                                                             ProductCode = pt.ProductCode,
                                                             NoteId = pt.NoteId,
                                                             ControlId = pt.ControlId
                                                         });

I also recommend, as you can see above, that you create a type for that select statement so that you're not relying on anonymous types. You should put in into an object type that you know everything about.

Also, if CourseCode is a string, that should be pt.CourseCode.Equals(course.CourseCode).

Upvotes: 1

Related Questions