Water
Water

Reputation: 1192

Nested for loop breaks to Linq

I'm pretty new to Linq and I am having troubles with creating the Linq equivalent of the below nested for loops:

for(int i = 0; i < toCompare1.Length; i++)
{
      bool isUnique = true;

      for(int j = 0; j < toCompare2.Length; j++)
      {
             if(toCompare1[i].Contains(toCompare2[j]))
             {
                 isUnique = false;
                 break;
             }
      }

      if(isUnique == true)
      {
          uniqueValues.Add(toCompare1[i]);
      }
}

Currently, my draft code is something like this:

var unique =
    from c1 in toCompare1
    from c2 in toCompare2
    where !c1.Contains(c2)
    select c1;

But it duplicates the entries I want to have.

Can anyone help me with this?

Thanks!

Upvotes: 1

Views: 43

Answers (1)

Steven Wexler
Steven Wexler

Reputation: 17299

In fluent syntax:

toCompare1.Where(item => !toCompare2.Any(item2 => item.Contains(item2)))

In query sytax:

from item1 in toCompare1
where !toCompare2.Any(item2 => item1.Contains(item2))
select item1;

Upvotes: 2

Related Questions