简体   繁体   中英

Filter generic list with array values in vb.net

I have an array of Colours Name and a Generic List of Products. I want to filter List which contains only products with the colours name in array same as Sql Like operator. eg '%Red%' . my code is following

Public Class Item
        Public Property ItemID() As Integer
        Public Property ItemName() As String
        Public Property RetailPrice() As Double
        Public Property Colour() as String
End Class

Dim ColourNames() As String = {"Red", "Blue", "Black", "Green"}
Dim filteredList = (From i In listItems Where i.ItemName.Contains(ColourNames)).ToList

EDIT: I've updated my example to match your updated question

Based on your example it looks like you intend ListItems to be the generic collection that contains your "Products".

Take your original ListItems Array and add the where() method to execute a LINQ query and get back only objects that match on the property from your ColourNames() Array.

    Dim ColourNames() As String = {"Red", "Blue", "Black", "Green"}
    Dim FilteredList = ListItems.Where(Function(i) ColourNames.Contains(i.Colour)).ToList

The Where() method will only return objects where the condition you specified is true. It loops through your ListItems and evaluates each current object (represented as i in this example because thats what you used in your question but you can use any variable name) to see if the colour property is contained in the ColourNames array.

If you need the contains method to be case-insensitive you just add a StringComparer.InvariantCultureIgnoreCase overload to it. This will better mirror the functionality you'd get from LIKE in SQL.

Dim FilteredList = ListItems.Where(Function(i) ColourNames.Contains(i.Colour, StringComparer.InvariantCultureIgnoreCase)).ToList

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM