Is there any simple way in c# to check if list consist of another list?. Here is example, I have:
var list1 = new List<int>() {1, 2, 3, 4, 5, 6,};
and second one
var list2 = new List<int>() {5, 6};
this list is a part of first list so it should return true.
var list1 = new List<int>() {1, 2, 3, 4, 5, 6,};
and
var list3 = new List<int>() {1, 3}; should return false.
It's not about checking if all elements in first list exist in second list but also about order. It has to have the same order.
all() method # Program to check the list contains elements of another list # List1 List1 = ['python' , 'javascript', 'csharp', 'go', 'c', 'c++'] # List2 List2 = ['csharp1' , 'go', 'python'] check = all(item in List1 for item in List2) if check is True: print("The list {} contains all elements of the list {}".
There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.
This works for me:
public bool ContainsSubsequence<T>(List<T> sequence, List<T> subsequence)
{
return
Enumerable
.Range(0, sequence.Count - subsequence.Count + 1)
.Any(n => sequence.Skip(n).Take(subsequence.Count).SequenceEqual(subsequence));
}
This code uses Enumerable.Range to run through every possible starting point within sequence that could be the same as subsequence, and checks if the segment of sequence the same size as subsequence at this position is actually equal to subsequence.
So for this code:
var list1 = new List<int>() { 1, 2, 3, 4, 5, 6, };
var list2 = new List<int>() { 5, 6, };
var list3 = new List<int>() { 1, 3, };
Console.WriteLine(ContainsSubsequence(list1, list2));
Console.WriteLine(ContainsSubsequence(list1, list3));
I get:
True
False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With