开发者

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


would this work:

listOfStrings.Contains("Trucks");


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜