IEnumerable.Flatten in C#

One thing I’ve seen fairly often is this:


public IEnumerable<Relationship> GetRelationships()
{
     var itemRels = (from i in DataContext.Items
                      select i.Relationships);

     var relList = new List<Relationship>();
     foreach (var rels in itemRels) {
          relList = relList.Concat(rels).ToList();
     }

     return relList;
}

This is essentially the same as the “Flatten” function that exists in many other languages, i.e.

var array = [1,2][3][4,5,6].flatten() // array = [1,2,3,4,5,6];

There is a built in extension for selecting objects like this in Linq :

     return Datacontext.Items.SelectMany(i => i.Relationships);

Leave a comment