Linq - Adding element to collection, Union vs Concat

Posted on 11:45am 1/21/2009 by Bruno Silva in .NET, Programming

Some time ago while developing a project I came across a problem related to Linq to Objects. I wanted do join a single object with a collection in order to transverse them with a foreach statement (the item was not allways present and I wanted to treat it as a regular element in the original collection).

Using the intellisense to find a Linq to Objects extension method that fitted my needs I didn’t find that particular functionality, but I thought about an alternative: creating a collection with the single element and joining the two collections with one of the two extension methods that seem promising to this new task: Union and Concat.

After reading the documentation and writing the example above I became aware of the difference. Union acts as a mathematical set operator, adding the elements of both lists into a single list without repeated elements. Contat, by the other hand keeps the repeated elements.


Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© Bruno Silva | Powered by Wordpress