我有两个列表,它们看起来像这样
<List> ads
[0]
Headline = "Sony Ericsson Arc silver"
[1]
Headline = "Sony Ericsson Play R800I"
<List> feedItems
[0]
Headline = "Sony Ericsson Xperia Arc Silver"
[1]
Headline = "Sony Ericsson Xperia Play R800i Black"
Run Code Online (Sandbox Code Playgroud)
创建新的第三个列表的最简单方法是什么,其中至少有两个单词相互匹配的元素?你能用LINQ方式完成这个吗?
第三个列表看起来像这样
[0]
AdHeadline = "Sony Ericsson Arc silver"
MatchingFeed = "Sony Ericsson Xperia Arc Silver"
// etc
Run Code Online (Sandbox Code Playgroud)
我已经尝试遍历第一个列表并使用Regex.Match类,如果我找到一个匹配,我填充第三个列表 - 我想知道你喜欢这样做的方式是什么,以及如何检查min.表达式中有2个以上的单词.
我不确定正则表达式会给聚会带来什么.以下怎么样?
// Define a helper function to split a string into its words.
Func<string, HashSet<string>> GetWords = s =>
new HashSet<string>(
s.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries)
);
// Pair up each string with its words. Materialize the second one as
// we'll be querying it multiple times.
var aPairs = ads.Select(a => new { Full = a, Words = GetWords(a) });
var fPairs = feedItems
.Select(f => new { Full = f, Words = GetWords(f) })
.ToArray();
// For each ad, select all the feeds that match more than one word.
// Then just select the original ad and feed strings.
var result = aPairs.SelectMany(
a => fPairs
.Where(f => a.Words.Intersect(f.Words).Skip(1).Any())
.Select(f => new { AdHeadline = a.Full, MatchingFeed = f.Full })
);
Run Code Online (Sandbox Code Playgroud)