如何将Linq结果值复制到DataTable [英] How to copy the Linq result value to DataTable

查看:119
本文介绍了如何将Linq结果值复制到DataTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个linq select查询我想将结果复制到数据表中。在这里,copytoDataTable没有到来。我正在从使用linq查询选择的grdiview中选择列值。如何将这个复制到Datatable。



Hi,

I am having a linq select query I want to copy that result to a datatable. In this the copytoDataTable is not coming. I am selecting the column value from the grdiview which is selected by using the linq query. How to copy this one to Datatable.

var result = (from GridViewRow msgRow in grdPrice.Rows
                    let ReferenceNO = ((HiddenField)msgRow.FindControl("hfReferenceNo")).Value
                    where ((CheckBox)msgRow.FindControl("chkSelect")).Checked
                     select new { ReferenceNO }).ToList();



谢谢


Thanks

推荐答案

你的结果是一个List(因为你在IEnumerable上调用了ToList) ) - 所以你可以使用这个:将列表转换为DataTable [ ^ ]。

如果不是,那么你必须稍微更改Tip中的代码以使其成为IEnumerable< T>而不是IList< T>
Your result is a List (since you called ToList on the IEnumerable) - so you can use this: Converting a List to a DataTable[^].
If it wasn't, then you'd have to change the code in the Tip a small amount to make it IEnumerable<T> instead of IList<T>


试试这个



Try This

public static class HelperFunctions
   {
       public static void Map<T>(this IEnumerable<T> source, Action<T> func)
       {
           foreach (T i in source)
               func(i);
       }

       public static DataTable ToDataTable<T>(this IEnumerable<T> source)
       {
           var dt = new DataTable();
           var properties = typeof(T).GetProperties();
           dt.Columns.AddRange(properties.Select(x => new DataColumn(x.Name, x.PropertyType)).ToArray());
           source.Select(x => dt.NewRow().ItemArray = properties.Select(y => y.GetValue(x, null)).ToArray()).Map(x => dt.Rows.Add(x));
           return dt;
       }
   }


这篇关于如何将Linq结果值复制到DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆