Linq 杂谈(之)IEnumerable<T> 转换 DataTable

本文提供两种将LINQ查询结果转换为DataTable的方法。一种是通过反射创建DataTable并填充数据,另一种是利用System.Data.Linq.DataContext的查询命令。这两种方法适用于不同的场景需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Sample I:

I created a public method called LINQToDataTable as following:

public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
     DataTable dtReturn = new DataTable();

     // column names 
     PropertyInfo[] oProps = null;

     if (varlist == nullreturn dtReturn;

     foreach (T rec in varlist)
     {
          // Use reflection to get property names, to create table, Only first time, others 
          will follow 
          if (oProps == null)
          {
               oProps = ((
Type)rec.GetType()).GetProperties();
               foreach (PropertyInfo pi in oProps)
               {
                    Type colType = pi.PropertyType;

                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()      
                    ==typeof(Nullable<>)))
                     {
                         colType = colType.GetGenericArguments()[0];
                     }

                    dtReturn.Columns.Add(
new DataColumn(pi.Name, colType));
               }
          }

          DataRow dr = dtReturn.NewRow();

          foreach (PropertyInfo pi in oProps)
          {
               dr[pi.Name] = pi.GetValue(rec, 
null) == null ?DBNull.Value :pi.GetValue
               (rec,null);
          }

          dtReturn.Rows.Add(dr);
     }
     return dtReturn;
}

---------------------------------------------------------------

Example: To use this method, just use the following code sample:

---------------------------------------------------------------

var vrCountry = from country in objEmpDataContext.CountryMaster
                        select new {country.CountryID,country.CountryName};

DataTable dt = LINQToDataTable(vrCountry);

Sample II

Here is my second method:

public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
{
     if (query == null)
     {
          throw new ArgumentNullException("query");
     }
     
     
IDbCommand
 cmd = ctx.GetCommand(query as IQueryable);
     SqlDataAdapter adapter = new SqlDataAdapter();
     adapter.SelectCommand = (
SqlCommand)cmd;
     DataTable dt = new DataTable("sd");

     try
     {
          cmd.Connection.Open();
          adapter.FillSchema(dt, 
SchemaType.Source); 
          adapter.Fill(dt);
     }
     finally
     {
          cmd.Connection.Close();
     }
     return dt;
}

---------------------------------------------------------------

Example: To use this method, just use the following code sample:

---------------------------------------------------------------

var vrCountry = from country in objEmpDataContext.CountryMaster
                        select new {country.CountryID,country.CountryName};

DataTable dt = LINQToDataTable(objEmpDataContext,vrCountry);

转载于:https://www.cnblogs.com/yangtongnet/archive/2010/07/06/1772314.html

<think>嗯,用户想知道如何在C#中将List<T>转换为IEnumerable<T>。首先,我需要回忆一下C#中集合类型的关系。记得List<T>实现了IList<T>接口,而IList<T>又继承自ICollection<T>和IEnumerable<T>。所以,List<T>本身已经是IEnumerable<T>的子类了,对吧?这样的话,直接赋值或者隐式转换应该就可以完成。 不过,用户可能不太清楚继承关系,可能需要具体例子说明。比如,可以直接将一个List<int>赋值给IEnumerable<int>变量,因为List<int>实现了IEnumerable<int>。例如: List<int> myList = new List<int>(); IEnumerable<int> myEnumerable = myList; 这样就可以了,不需要显式转换,因为这是隐式转换的。另外,可能还需要提到使用AsEnumerable()方法,虽然对于List<T>来说可能不是必须的,但这个方法可以将集合显式转换为IEnumerable<T>。例如: IEnumerable<int> myEnumerable = myList.AsEnumerable(); 不过,这种情况下可能和直接赋值效果一样,但AsEnumerable()在处理其他类型如数组时可能更有用。另外,需要注意转换后的IEnumerable<T>只能进行迭代操作,不能像List<T>那样修改元素,比如添加或删除。 用户可能还会有疑问,比如为什么要转换?可能是因为某些方法参数接受IEnumerable<T>类型,而他们有一个List<T>需要传入。这时候转换就能保持灵活性,同时遵循接口隔离原则。 还要注意,转换后的IEnumerable<T>会引用原始List<T>,所以修改List<T>的内容会影响转换后的枚举结果。此外,可能需要提醒用户转换后的性能影响,比如延迟执行的情况,但在这里可能不适用,因为List<T>已经实现了IEnumerable<T>。 最后,可能需要给出示例代码,展示这两种方法,并说明适用场景,确保用户理解不同方法之间的区别和选择依据。</think>在C#中将$List<T>$转换为$IEnumerable<T>$的方法如下,基于它们的继承关系实现: ### 方法1:直接隐式转换 由于$List<T>$直接实现了$IEnumerable<T>$接口,可以直接赋值: ```csharp List<string> list = new List<string>(); IEnumerable<string> enumerable = list; // 隐式转换 ``` ### 方法2:使用AsEnumerable() 通过LINQ扩展方法显式转换: ```csharp IEnumerable<int> numbers = new List<int>{1,2,3}.AsEnumerable(); ``` ### 原理说明 1. $List<T>$继承链:$List<T> : IList<T> : ICollection<T> : IEnumerable<T>$ 2. 转换后的$IEnumerable<T>$将保留原始集合的引用,对原$List<T>$的修改会影响转换结果 3. 转换后只能使用迭代器方法(如foreach),无法使用列表特有操作(如Add/Remove)[^1][^3] ### 应用场景 - 需要向接收$IEnumerable<T>$参数的方法传递集合 - 实现延迟执行查询 - 隐藏集合的具体实现细节 $$注意:当需要反向转换时(IEnumerable<T>转List<T>),应使用ToList()方法$$
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值