考虑我们有这三个列表:
List<string> l1= new List<string>(){"A","B","C"};
List<string> l2= new List<string>(){"A","C","B"};
List<string> l3= new List<string>(){"B","C"};
我需要 LINQ 查询,它说 l1 包含 l3 但 l2 不包含。
最佳答案
为了尊重顺序并考虑到可能的重复元素,您必须枚举序列,一种方法是检查源枚举中的每个开始位置,如果另一个序列从这里开始,例如使用扩展方法:
public static bool ContainsSequence<T>(this IEnumerable<T> source,
IEnumerable<T> other)
{
int count = other.Count();
while (source.Any())
{
if (source.Take(count).SequenceEqual(other))
return true;
source = source.Skip(1);
}
return false;
}
请注意,这将是 O(n2),因为最坏的情况是您已经为 source
中的每个项目完全枚举了 other
枚举收藏。
现在您可以:
List<string> l1 = new List<string>() { "A", "B", "C" };
List<string> l2 = new List<string>() { "A", "C", "B" };
List<string> l3 = new List<string>() { "B", "C" };
bool l1ContainsL2 = l1.ContainsSequence(l2); //returns false
bool l1ContainsL3 = l1.ContainsSequence(l3); //returns true
关于c# - Linq 查询列表包含具有相同顺序的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9183892/