Add a column to an IEnumerable in c#

Knox picture Knox · Mar 17, 2011 · Viewed 15.4k times · Source

I don't think I can actually add a field (column) to an existing IEnumerable. But what I want is a new IEnumerable that is derived from an existing IEnumerable with a calculated field. The pseudocode in WebMatrix using Web Pages looks like:

var db = Database.Open("LOS");
var ie = db.Query(sqlAssignments);

// make a new ie2 that has an extra field
// ??? ie2 <=== ie with new field c = ie.a + ie.b

var grid = new WebGrid( ie2, extra parameters );

I know how to do this looping through all the rows in ie. But I'm hoping there's something more elegant.

Answer

Marc Gravell picture Marc Gravell · Mar 17, 2011

How about:

var ie2 = ie.Select(x => new { x.Foo, x.Bar, Sum = x.Abc + x.Def });
var grid = new WebGrid(ie2);