简体   繁体   中英

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

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?

Vehicles.Where(v => listOfStrings.Contains(v.Name))

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));

这会工作:

listOfStrings.Contains("Trucks");
var m = Vehicles.Where(v => listOfStrings.Contains(v.Name));

To check if a string contains one of these characters (Boolean output):

var str= "string to test";
var chr= new HashSet<char>{',', '&', '.', '`', '*', '$', '@', '?', '!', '-', '_'};
bool test = str.Any(c => chr.Contains(c));

You can perform an Inner Join :

var matchingVehicles = from vehicle in vehicles
                       join item in listOfStrings on vehicle.Name equals item
                       select vehicle;
Vehicles.Where(vehicle => listOfStrings.Contains(vehicle.Name))

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