Nick
Nick

Reputation: 4223

LINQ to Objects - Is not in?

I have a generic list of custom objects and would like to reduce that list to objects where a specific property value is not in a list of exclusions.

I have tried the following:

Private Sub LoadAddIns()
  // Get add-in templates
  Dim addIns = GetTemplates(TemplateTypes.AddIn)
  // Get the current document
  Dim sectionId As String = CStr(Request.QueryString("sectionId"))
  Dim docId As Integer = CInt(Split(sectionId, ":")(0))
  Dim manual = GetTempManual(docId)
  Dim content As XElement = manual.ManualContent
  // Find which templates have been used to create this document.
  Dim usedTemplates = (From t In content.<header>.<templates>.<template> _
                       Select CInt(t.<id>.Value)).ToList
  // Exclude add-ins that have already been used.
  If usedTemplates IsNot Nothing Then
    addIns = addIns.Where(Function(a) usedTemplates.Contains(a.TemplateID) = False)
  End If
  // Bind available add-ins to dropdown
  With ddlAddIns
    .DataSource = addIns
    .DataTextField = "Title"
    .DataValueField = "TemplateID"
    .DataBind()
    .Items.Insert(0, New ListItem("[select an add-in]", 0))
  End With
End Sub

but get the error:

System.InvalidCastException: Unable to cast object of type 'WhereListIterator1[MyApp.Classes.Data.Entities.Template]' to type 'System.Collections.Generic.List1[MyApp.Classes.Data.Entities.Template]'.

How can I select only the templates where the template id is not in the list of exclusions?

Upvotes: 2

Views: 5239

Answers (1)

tvanfosson
tvanfosson

Reputation: 532565

Tack a ToList() extension to the end of the Where extension to convert it back to a List of the appropriate type.

If usedTemplates IsNot Nothing Then
    addIns = addIns.Where(Function(a) usedTemplates.Contains(a.TemplateID) = False) _
                   .ToList()
End If

Upvotes: 5

Related Questions