如何确定字符串是否包含字符串列表的任何匹配项

时间:2022-09-19 20:51:38

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.

我想找到名称与listOfStrings中的一个项目匹配的车辆。

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

我正试图用linq做这个,但目前似乎无法完成它。

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

Can anybody help me with this?

任何人都可以帮我吗?

7 个解决方案

#1


13  

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

#2


12  

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

使用HashSet而不是List,这样您就可以查找字符串而无需遍历列表。

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

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

现在,您可以使用Contains方法有效地查找匹配项:

var matchingVehicles = Vehicles.Where(v => setOfStrings.Contains(v.Name));

#3


6  

would this work:

这会工作:

listOfStrings.Contains("Trucks");

#4


1  

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

#5


0  

You can perform an Inner Join:

您可以执行内部联接:

var matchingVehicles = from vehicle in vehicles
                       join item in listOfStrings on vehicle.Name equals item
                       select vehicle;

#6


0  

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

#7


0  

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

#1


13  

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

#2


12  

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

使用HashSet而不是List,这样您就可以查找字符串而无需遍历列表。

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

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

现在,您可以使用Contains方法有效地查找匹配项:

var matchingVehicles = Vehicles.Where(v => setOfStrings.Contains(v.Name));

#3


6  

would this work:

这会工作:

listOfStrings.Contains("Trucks");

#4


1  

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

#5


0  

You can perform an Inner Join:

您可以执行内部联接:

var matchingVehicles = from vehicle in vehicles
                       join item in listOfStrings on vehicle.Name equals item
                       select vehicle;

#6


0  

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

#7


0  

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