LINQ Query using 'StartsWith' with an array

In My LINQ Query I use Where Clauses to check whether a property exists within an array of values. I would like to update the query:

string[] itemColour
string[] itemType

List<displayItem> displayItems = (from item in allItems
                                  Where itemColour.Contains(item.colour)
                                  Where itemType.Contains(item.type)
                                  select new displayItem
                                  ......................etc...etc

So what I have is

'Where my 'itemColour' array contains this 'item.colour' select it'

'Where my 'itemType' array contains this 'item.type' select it'

What I'm after is

'Where my 'itemColour' array has an item that has 'item.colour' anywhere in it select it
'Where my 'itemType' array has an item that begins with 'item.type' select it

I'm aware of 'StartsWith' and 'EndsWith' but don't know how to use them with these arrays.

note: itemColour may contain an item that has the colour code 'RGW' I would want to be able to select this item based on any of the three letters

Update

The suggested solution :

var query = from item in allItems
        where itemColour.Any(c => c.Contains(item.colour))
           && itemType.Any(t => t.StartsWith(item.type)
        select ...;

has an issue. If I'm trying to bring back an item with the colour Code 'RB'. My Array may contain two items 'R' and 'B' the suggested query is only returning items with colour code either 'R' or 'B' not both.

I am using MVC 5, LINQ TO Entity, .NET 4.5

Thanks

Jon Skeet
people
quotationmark

I suspect you're looking for Any, which allows you to check whether any item in a sequence (the arrays in this case) matches a predicate:

var query = from item in allItems
            where itemColour.Any(c => c.Contains(item.colour))
               && itemType.Any(t => t.StartsWith(item.type)
            select ...;

There are potential optimizations depending on how many colour entries you have and the exact semantics.

If you want to find items which match either colour or type, use || instead:

var query = from item in allItems
            where itemColour.Any(c => c.Contains(item.colour))
               || itemType.Any(t => t.StartsWith(item.type)
            select ...;

EDIT: Your description isn't clear, but it's entirely possible that you really want:

 itemColour.Any(c => item.colour.Contains(c))

instead. Think logically about what you want to check, and apply it appropriately.

people

See more on this question at Stackoverflow