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

爷,独闯天下 提交于 2019-12-24 07:39:19

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!