How to convert DataView,DataRowView to Generic Typed Lists

点点圈 提交于 2019-12-24 11:37:09

问题


Is there any possible method than looping, Enumerating the ICollection to convert them respectively to Typed List knowing the columns in the ICollection. I am using .net Framework 2.0, C#2.0. Expected answer would be something like this,a one liner

List<Bills> bills = GetBills(DataView/DataRowView/ICollection);

where Bills type would have BillNumber, BillDate, BilledTo as properties. The DataRowView/DataView would have corresponding Columns with records in them. Is there a factory build method that does the Job? If No any one liner to do it?


回答1:


Could you do it in one line using a LINQ Select with a lambda? Something along these lines....

List<Bills> bills = yourDataView.Rows.Select(t => new Bills() {BillNumber = t["BillNumber"], BillDate = t["BillDate"], BilledTo = t["BilledTo"]}).ToList();



回答2:


Use Linq Select to convert the DataView rows to a List of objects:

DataView yourDataView;

List<Bills> bills = yourDataView.ToTable().Rows.Cast<DataRow>()
                    .Select(r => new Bills() 
                    { 
                        BillNumber = r.Field<int>("BillNumber"), 
                        BillDate = r.Field<DateTime>("BillDate"), 
                        BilledTo = r["BilledTo"].ToString()                 
                    }).ToList();


来源:https://stackoverflow.com/questions/6276137/how-to-convert-dataview-datarowview-to-generic-typed-lists

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