问题
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?
回答1:
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 }
}
来源:https://stackoverflow.com/questions/5339335/add-a-column-to-an-ienumerable-in-c-sharp-such-that-it-works-with-webgrid