2016-01-23 59 views
2

我有這樣的字符串:var str = "My name is John, her name is Fonda and his name is Donald"C# - 如何使用Linq和Regex從單個字符串實現多個匹配?

和我有一個可枚舉集等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

提前感謝!

+2

正則表達式將是「(約翰福音|方達|唐納德|邁克|羅傑)」,該管的或聲明,一切之間發現了什麼。括號內是捕獲的數據。 – Vince

+0

謝謝文斯!它真的幫助了我。我會盡力在上面構建答案! – MrGorki

+0

我還沒有給出我的答案,但我正在考慮一個PLINQ,其中每個元素('男孩,女孩,兒子,其他'或'other2')遍歷有問題的字符串('我的名字是約翰,她的名字是方達,他的名字是唐納德)將是你想要走的方向。 – code4life

回答

1

您可以使用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)); 
+0

我覺得很愚蠢:) – MrGorki

+0

如果'resultSet'包含名稱「Don」而不是名稱「Donald」,那麼這種方法將返回「Don」對象 – Fabio

+0

用'Split'添加方法,將不會得到「John」結果,因爲「,」char – Fabio

1

你可以用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" 

注:最重要的是,使用Containswhere這裏

0

試試這個

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