更新以涵盖任一情况:
您可以通过adding spaces before capital letters 获取来自text 的单词列表并在空间上进行拆分。然后您可以使用SequenceEqual() 将该结果与list 进行比较。
这是一个例子:
static void Main(string[] args)
{
List<string> list = new List<string> {"One", "Two", "Three", "Four", "Five" };
string text = "OneTwoThreeFourFive";
string withSpaces = AddSpacesToSentence(text, true);
List<string> list2 = withSpaces.Split(' ').ToList();
bool b = list.SequenceEqual(list2);
}
// Refer to: https://stackoverflow.com/a/272929/4551527
static string AddSpacesToSentence(string text, bool preserveAcronyms)
{
if (string.IsNullOrWhiteSpace(text))
return string.Empty;
StringBuilder newText = new StringBuilder(text.Length * 2);
newText.Append(text[0]);
for (int i = 1; i < text.Length; i++)
{
if (char.IsUpper(text[i]))
if ((text[i - 1] != ' ' && !char.IsUpper(text[i - 1])) ||
(preserveAcronyms && char.IsUpper(text[i - 1]) &&
i < text.Length - 1 && !char.IsUpper(text[i + 1])))
newText.Append(' ');
newText.Append(text[i]);
}
return newText.ToString();
}
请注意,我从这个答案中获得了 AddSpacesToSentence 的实现:https://stackoverflow.com/a/272929/4551527
另一个更新
顺便说一句,如果列表中单词的顺序不重要(换句话说:“OneTwo”应该匹配{“Two”,“One”}),那么你可以在做之前Sort()两个列表SequenceEquals()
原创(当我认为这是单向比较时)
您可以改用All():
List<string> list = new List<string> {"One", "Two", "Three", "Four" };
string text = "OneTwoThreeFour";
list.All(s => text.Contains(s))
如果序列中的所有元素都满足谓词(这里是包含),这将返回 true。
上面的sn-p返回true。如果将“五”添加到 list(但保持 text 相同),那么它将返回 false。