title: Nested foreach loop to lambda-expressions
body: <p>I'm currently refactoring a project I'm doing at the university I'm attending. Part of this refactoring is to make parts of the project more concise, and use less code. Some times I run several foreach loops and add stuff to a List.</p>
  
  <p>I have the following code-chunk which works as intended </p>
  
  <pre><code>private List&lt;Literal&gt; GetClashingLiterals(ClauseNode other)
  {
      List&lt;Literal&gt; clashes = new List&lt;Literal&gt;();
      foreach (Literal literal in literals)
      {
          foreach (Literal otherlit in other.literals)
          {
              if (literal.Name.Equals(otherlit.Name) 
                  &amp;&amp; !(literal.Sign.Equals(otherlit.Sign)))
              {
                  clashes.Add(literal);
              }
          }
      }
      return clashes;
  }
  </code></pre>
  
  <p>I would like to transform this piece of code to a lambda expression. I found this old question here on stackoverflow <a href="https://stackoverflow.com/questions/5418839/c-sharp-populate-a-list-using-lambda-expressions-or-linq">C# - Populate a list using lambda expressions or LINQ</a>.</p>
  
  <p>I thought it was just what i needed, so I made this lambda-expresison and tested it:</p>
  
  <pre><code>List&lt;Literal&gt; clashes = (List&lt;Literal&gt;)literals
      .Where(lit =&gt; other.literals
          .Any(lit2 =&gt; lit.Name.Equals(lit2.Name) 
              &amp;&amp; !lit.Sign.Equals(lit2.Sign)));
  </code></pre>
  
  <p>However it doesn't work. I get an InvalidCastException whenever i try to run it. Without the cast, it doesn't compile! So what am i missing?</p>
  
  <p>This is the exception:</p>
  
  <blockquote>
    <p>Unable to cast object of type 'WhereEnumerableIterator<code>1[Heureka.Model.Literal]' to type 'System.Collections.Generic.List</code>1[Heureka.Model.Literal]'.</p>
  </blockquote>