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

发布于 2024-10-25 11:54:09 字数 358 浏览 0 评论 0原文

你好,说我有一个字符串列表:

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

我有一个带有名称字段的车辆选项。

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

我正在尝试使用 linq 来完成此操作,但目前似乎无法完成。

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

有人能帮我解决这个问题吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

水中月 2024-11-01 11:54:09
Vehicles.Where(v => listOfStrings.Contains(v.Name))
Vehicles.Where(v => listOfStrings.Contains(v.Name))
以为你会在 2024-11-01 11:54:09

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

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

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

var matchingVehicles = Vehicles.Where(v => setOfStrings.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));
烟酉 2024-11-01 11:54:09

这会起作用吗:

listOfStrings.Contains("Trucks");

would this work:

listOfStrings.Contains("Trucks");
倦话 2024-11-01 11:54:09
var m = Vehicles.Where(v => listOfStrings.Contains(v.Name));
var m = Vehicles.Where(v => listOfStrings.Contains(v.Name));
万劫不复 2024-11-01 11:54:09

您可以执行内部联接

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

You can perform an Inner Join:

var matchingVehicles = from vehicle in vehicles
                       join item in listOfStrings on vehicle.Name equals item
                       select vehicle;
家住魔仙堡 2024-11-01 11:54:09
Vehicles.Where(vehicle => listOfStrings.Contains(vehicle.Name))
Vehicles.Where(vehicle => listOfStrings.Contains(vehicle.Name))
(り薆情海 2024-11-01 11:54:09

要检查字符串是否包含以下字符之一(布尔输出):

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

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));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文