Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a string contains any matches of a list of strings

Tags:

c#

asp.net

linq

Hi say I have a list of strings:

var listOfStrings = new List<string>{"Cars", "Trucks", "Boats"};

and I have a vehicles options which has a Name field.

I want to find the vehicles where the name matches one of the items in the listOfStrings.

I'm trying to do this with linq but can't seem to finish it at the moment.

var matchingVehicles = Vehicles.Where(v => v.Name == one of the listOfStringItem)

Can anybody help me with this?

like image 597
Coder 2 Avatar asked Mar 23 '11 22:03

Coder 2


3 Answers

Vehicles.Where(v => listOfStrings.Contains(v.Name))
like image 144
Daniel A. White Avatar answered Oct 01 '22 11:10

Daniel A. White


Use a HashSet instead of a List, that way you can look for a string without having to loop through the list.

var setOfStrings = new HashSet<string> {"Cars", "Trucks", "Boats"};

Now you can use the Contains method to efficiently look for a match:

var matchingVehicles = Vehicles.Where(v => setOfStrings.Contains(v.Name));
like image 29
Guffa Avatar answered Oct 01 '22 11:10

Guffa


would this work:

listOfStrings.Contains("Trucks");
like image 23
Rob Avatar answered Oct 01 '22 12:10

Rob