我完全支持@Jon 给出的答案。它非常快速、简洁和精确。我仍然有一种完全不同的方法,一种更实用的方法,以防万一string[]
你真的想说一些更流畅的东西:
假设您有一个可能无限的字符串序列,而不是 B 角色的原始数组。它可以是任何东西:直接从数据库读取实体,单子字符串生成器,任何东西:
string[] A = ["word1", "word2", "word3"];
IEnumerable[] B = ...;
您可以为自己编写一个不错的小扩展方法:
public static class MyHelpers {
public static IEnumerable<string> ReplaceFirstOccurrencesWithEmpty(this IEnumerable<string> @this, IEnumerable<string> a) {
// prepare a HashSet<string> to know how many A elements there still exist
var set = new Hashset<string>(a);
// iterate and apply the rule you asked about
// virtually forever (if needed)
foreach (var value in @this) {
if (set.Remove(value))
yield return "";
else
yield return value;
}
}
}
然后你可以像这样使用它,即使在你最初的 A 和 B 数组上:
string[] A = ["word1", "word2", "word3"];
string[] B = ["word0", "word1", "word2", "word3", "word4", "word5", "word6", "word1", "word2", "word3"];
var cQuery = B.ReplaceFirstOccurrencesWithEmpty(A);
string[] c = cQuery.ToArray();