我有以下代碼:排除從Linq查詢排除一切結果
public IList<Tweet> Match(IEnumerable<Tweet> tweetStream, IList<string> match, IList<string> exclude)
{
var tweets = from f in tweetStream
from m in match
where f.Text.ToLowerInvariant().Contains(m)
select f;
var final = from f in tweets
from e in exclude
where !f.Text.ToLowerInvariant().Contains(e.ToLowerInvariant())
select f;
return final.Distinct().ToList<Tweet>();
}
我已經建立還沒有包括final
結果集,現在已經幸福地匹配我的測試已添加排除,如果IList<string>exclude
爲空,則刪除所有項目。
所以這個測試通過,因爲它應該:
[TestMethod]
public void Should_exclude_items_from_exclude_list()
{
IEnumerable<Tweet> twitterStream = new List<Tweet>
{
new Tweet("I have a Mazda car"),
new Tweet("I have a ford"),
new Tweet("Mazda Rules"),
new Tweet("My Ford car is great"),
new Tweet("My renault is brill"),
new Tweet("Mazda cars are great")
};
IList<string> matches = new List<string>{"mazda","car"};
IList<string> exclude = new List<string>{"ford"};
Matcher target = new Matcher();
IList<Tweet> actual = target.Match(twitterStream, matches, exclude);
Assert.AreEqual(3, actual.Count);
}
但現在測試失敗:
[TestMethod]
public void Should_match_items_either_mazda_or_car_but_no_duplicates()
{
IEnumerable<Tweet> twitterStream = new List<Tweet>
{
new Tweet("I have a Mazda car"),
new Tweet("I have a ford"),
new Tweet("Mazda Rules"),
new Tweet("My Ford car is great"),
new Tweet("My renault is brill"),
new Tweet("Mazda cars are great")
};
IList<string> matches = new List<string>{"mazda","car"};
IList<string> exclude = new List<string>();
Matcher target = new Matcher();
IList<Tweet> actual = target.Match(twitterStream, matches, exclude);
Assert.AreEqual(4, actual.Count);
}
我知道我失去了一些東西很簡單,但在代碼盯着一個小時後,它不會來到我身邊。
@JonSkeet,其實我打你的答案,世界即將結束。 :D – msarchet 2011-02-23 22:25:02
@msarchet:不公平,我的妻子需要幫忙評價一件衣服:)(而且我更喜歡我的答案,因爲我現在指定的原因。) – 2011-02-23 22:26:46
@JonSkeet,是的,它是我的乾淨版 – msarchet 2011-02-23 22:27:23