Your query should actually "work," but it's not going to be very efficient if your list size is particularly large. If you're having troubles compiling, check to be sure you do not have any typos. If you're having problems at runtime, add some null checks on your variables and properties. The rest of this answer is to guide how you might utilize Linq to make your query better.
Given the query you have attempted to write, I am going to infer the following closely approximates the relevant parts of your class structure, though I'm using different name for what you have as "multival."
class Foo
{
public string Name { get; set; }
public string[] Attributes { get; set; }
}
And then given an object list looking roughly like this
var mylist = new List<Foo>
{
new Foo { Name = "Alpha", Attributes = new[] { "A", "B", "C" } },
new Foo { Name = "Bravo", Attributes = new[] { "D", "E", "F" } },
new Foo { Name = "Charlie", Attributes = new[] { "G", "H", "A" } }
};
For finding objects that match any other object based on any match of an attribute, this is how I would approach it using Linq:
var part1 = from item in mylist
from value in item.Attributes
select new { item, value };
var query = (from pairA in part1
join pairB in part1 on pairA.value equals pairB.value
where pairA.item.Name != pairB.item.Name
select pairA.item)
.Distinct(); // ToList() to materialize, as necessary
If you were to run that through your editor of choice and explore the contents of part2
, you would expect to see objects "Alpha" and "Charlie" based on the shared attribute of "A".
This approach should scale much better than a nested foreach should the size of your initial list be significant (for example, your list containing 10,000 elements instead of 3), which is precisely what your initial approach is.