C# - 如何使用 Linq 和 Regex 从单个字符串实现多个匹配
本文关键字:实现 字符串 单个 何使用 Linq Regex | 更新日期: 2023-09-27 18:31:30
我有一个字符串,如下所示:var str = "My name is John, her name is Fonda and his name is Donald"
我在可枚举集合中有 3 个对象,例如:
var boy = new Person({name="John"});
var girl = new Person({name="Fonda"});
var son = new Person({name="Donald"});
new other = new Person({name="Mike"});
new other2 = new Person({name="Roger"});
假设resultSet
包含上述所有对象。
var resultSet = new IEnumerable<Person>();
这是我的问题:
我想对该集进行 Linq 查询,以返回所有匹配的对象(如果它们在给定字符串中)。
我认为这很可能通过使用正则表达式来实现,但我不知道如何:S
提前感谢!
您可以使用Contains
方法:
var str = "My name is John, her name is Fonda and his name is Donald";
var result= resultSet.Where(p=>str.Contains(p.name));
如果要避免部分结果,可以将Split
应用于句子,并使用扩展方法执行以下查询Any
:
var str = "My name is John, her name is Fonda and his name is Donald";
var strArray= str.Split( new [] {' ', ','});
var result= resultSet.Where(p=>strArray.Any(s=>s==p.name));
您可以使用
LINQ 解决它:
var str = "My name is John, her name is Fonda and his name is Donald";
var strs = str.Split(new char[] {' ', ','}); //note the comma here is needed to get "John"
var names = from p in resultSet
where strs.Contains(p.name)
select p.name; //or select p if you need the "Person"
注意:最重要的是,在此处使用Contains
和where
试试这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Person> people = new List<Person>();
var boy = new Person() {name="John"};
var girl = new Person() {name="Fonda"};
var son = new Person() {name="Donald"};
var other = new Person() {name="Mike"};
var other2 = new Person(){name="Roger"};
people.AddRange(new Person[] { boy, girl, son, other, other2 });
string str = "My name is John, her name is Fonda and his name is Donald";
string[] peopleInSentenance = people.Where(x => str.Contains(x.name)).Select(y => y.name).ToArray();
}
}
public class Person
{
public string name { get; set; }
}
}