So you give us some code that doesn't do what you want, and you want us to write code that does do what you want.
Wouldn't it be nice if you told us what your want?
I'll try to make a good guess.
So you have a sequence of Tests
, where every Test
has a property Tags
, which is a sequence of strings.
You also have a sequence of Tags
, which is also a sequence of strings.
IEnumerable<Test> tests = ...
IEnumerable<string> tags = ...
Which of the following four do you want?
I want only those Tests that have
- a value for property Tags equal to Tags (same values, same order)
- exactly the same Tags that are in tags (same values, any order)
- have at least all Tags that are in sequence of Tags (more values)
- have only Tags that are in my sequence of Tags (less values)
Tags equal to tags: same value, same order
For this, use one of the overloads of Enumerable.SequenceEqual
var result = tests.Where(test => test.Tags.SequenceEqual(tags));
In words: from all tests
, keep only those Tests that have a sequence of strings in property Tags
that is exactly the same sequence as we have in tags
: same number of strings, in the same order.
If you want, you can use an equality comparer, for instance:
IEqualityComparer<string> tagComparer = StringComparer.OrdinalIgnoreCase;
var result = tests.Where(test => test.Tags.SequenceEqual(tags, tagComparer));
Exactly the same Tags that are in tags: same values, any order
For this it is wise to put your tags in a HashSet<string>
, this is a fast method to see if two sequences have the same elements:
HashSet<string> setTags = new HashSet<string>(tags);
var result = tests.Where(test => setTags.SetEquals(test.Tags));
SetEquals returns true if exactly the same elements, in any order, duplicates are ignored.
Or course, you can use an equality comparer:
HashSet<string> setTags = new HashSet<string>(tags, tagComparer);
There is a wee problem here:
tags = new string[] {"1", "1", "1", "1","1", "1", "1", "1"}
Test = new Test
{
Tags = new string[] {"1", "1"},
...
}
Do you want to keep this test? Let's ignore the duplicates.
at least all Tags that are in sequence of Tags: more values
Once you've created the HashSet, the other two are easy
At least all Tags that are in sequence of Tags: more values
var result = tests.Where(test => setTags.IsSuperSetOf(test.Tags));
Only Tags that are in my sequence of Tags: less values
var result = tests.Where(test => setTags.IsSubSetOf(test.Tags));