Add a column to an IEnumerable in c# such that it works with WebGrid
Asked Answered
F

1

1

In this question, Add a column to IEnumerable in C#, I got the following code:

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

// make a new ie2 that has an extra calculated field
var ie2 = processes.Select( e => new { e.ACCT,  e.RefID, color = e.RefID + 9000000 });

var grid = new WebGrid(ie2.ToList(), rowsPerPage : 50, ajaxUpdateContainerId : "grid" );

The data correctly shows up, however the grid no longer sorts. It sorts fine if you pass ie, instead of ie2. It has the problem if I do the ToList() or not. Obviously there's some difference between ie and ie2. Here's the GetType for ie:

System.Collections.ObjectModel.ReadOnlyCollection`1[System.Object]

and for ie2:

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Object,<>f__AnonymousType0`10[System.Object,System.Object,System.Object,System.Object,System.Object,System.Object,System.Object,System.Object,System.Object,System.Object]]

What should I do to ie2 to make it work with WebGrid and sort correctly?

Foresight answered 17/3, 2011 at 13:0 Comment(0)
G
2

Try to create a type for ie2 instead of using an anonymous type, like:

var ie2 = processes.Select( e => 
   new MyNewType { ACCT = e.ACCT, RefID = e.RefID, Color = e.RefID + 9000000 }
);

Where the new type would be:

class MyNewType {
   public string ACCT { get; set }
   public int RefID { get; set }
   public int Color { get; set }
}
Gretagretal answered 17/3, 2011 at 13:5 Comment(2)
I took a wild guess based on the fact that in order to perform certain things like sorting, logic might depend on names. It needs something to work with. Anonymous types are excellent in a very limited scope. As soon as you leave that small scope, you need a type that can be accessed.Planula
Excellent wild guess. Thanks again.Foresight

© 2022 - 2024 — McMap. All rights reserved.