Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a column to an IEnumerable in c#

Tags:

c#

linq

webmatrix

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.

like image 524
Knox Avatar asked Mar 17 '11 11:03

Knox


2 Answers

How about:

var ie2 = ie.Select(x => new { x.Foo, x.Bar, Sum = x.Abc + x.Def });
var grid = new WebGrid(ie2);
like image 76
Marc Gravell Avatar answered Oct 20 '22 18:10

Marc Gravell


You can do this using Select. Try this:

ie2 = ie.Select( e => new { IE = e, NewParam =  e.X+e.Y });
like image 41
Øyvind Bråthen Avatar answered Oct 20 '22 18:10

Øyvind Bråthen