博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

IList转DataTable

Posted on 2008-04-01 11:44  codingsilence  阅读(599)  评论(0编辑  收藏  举报
        #region 数据集互操作

        
/// <summary>
        
/// 将集合类转换成DataTable
        
/// </summary>
        
/// <param name="list">集合</param>
        
/// <returns></returns>
        public static DataTable ToDataTable(IList list)
        {
            DataTable result 
= new DataTable();
            
if (list.Count > 0)
            {
                PropertyInfo[] propertys 
= list[0].GetType().GetProperties();
                
foreach (PropertyInfo pi in propertys)
                {
                    result.Columns.Add(pi.Name, pi.PropertyType);
                }

                
for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList 
= new ArrayList();
                    
foreach (PropertyInfo pi in propertys)
                    {
                        
object obj = pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                    
object[] array = tempList.ToArray();
                    result.LoadDataRow(array, 
true);
                }
            }
            
return result;
        }

        
/// <summary>
        
/// 将泛型集合类转换成DataTable
        
/// </summary>
        
/// <typeparam name="T">集合项类型</typeparam>
        
/// <param name="list">集合</param>
        
/// <returns>数据集(表)</returns>
        public static DataTable ToDataTable<T>(IList<T> list)
        {
            
return  ConvertX.ToDataTable<T>(list, null);
        }

        
/// <summary>
        
/// 将泛型集合类转换成DataTable
        
/// </summary>
        
/// <typeparam name="T">集合项类型</typeparam>
        
/// <param name="list">集合</param>
        
/// <param name="propertyName">需要返回的列的列名</param>
        
/// <returns>数据集(表)</returns>
        public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
        {
            List
<string> propertyNameList = new List<string>();
            
if (propertyName != null)
                propertyNameList.AddRange(propertyName);

            DataTable result 
= new DataTable();
            
if (list.Count > 0)
            {
                PropertyInfo[] propertys 
= list[0].GetType().GetProperties();
                
foreach (PropertyInfo pi in propertys)
                {
                    
if (propertyNameList.Count == 0)
                    {
                        result.Columns.Add(pi.Name, pi.PropertyType);
                    }
                    
else 
                    {
                        
if (propertyNameList.Contains(pi.Name))
                            result.Columns.Add(pi.Name, pi.PropertyType);
                    }
                }

                
for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList 
= new ArrayList();
                    
foreach (PropertyInfo pi in propertys)
                    {
                        
if (propertyNameList.Count == 0)
                        {
                            
object obj = pi.GetValue(list[i], null);
                            tempList.Add(obj);
                        }
                        
else
                        {
                            
if (propertyNameList.Contains(pi.Name))
                            {
                                
object obj = pi.GetValue(list[i], null);
                                tempList.Add(obj);
                            }
                        }
                    }
                    
object[] array = tempList.ToArray();
                    result.LoadDataRow(array, 
true);
                }
            }
            
return result;
        }

        
#endregion
    }

    
public class ConvertXToDataTableTester : ITest
    {
        
#region ITest 成员

        
public string Name
        {
            
get { return new ConvertXToDataTableTester().GetType().Name; }
        }

        
public void StartRuntime()
        {
            
//Test1(ToDataTable<>):boundary
            CollectionBase<Item> items1 = new CollectionBase<Item>();
            items1.Add(
new Item("item1_1"1));
            items1.Add(
new Item("item1_2""null"));
            items1.Add(
new Item("item1_3"3));

            DataTable dt 
= ConvertX.ToDataTable<Item>(items1);

            
foreach (DataRow dr in dt.Rows)
            {
                Console.WriteLine(
"{0},{1}", dr["text"].ToString(), dr[1].ToString());
            }

            
//Test2(ToDataTable):
            ArrayList items2 = new ArrayList();
            items2.Add(
new Item("item2_1"3));
            items2.Add(
new Item("item2_2"4));
            items2.Add(
new Item("item2_3"5));

            DataTable dt2 
= ConvertX.ToDataTable(items2);

            
foreach (DataRow dr in dt2.Rows)
            {
                Console.WriteLine(
"{0},{1}", dr["text"].ToString(), dr[1].ToString());
            }

            
//Test3(ToDataTable<>):
            IList<Item> items3 = new CollectionBase<Item>();
            items3.Add(
new Item("item3_1"3));
            items3.Add(
new Item("item3_2"4));
            items3.Add(
new Item("item3_3"5));

            DataTable dt3 
= ConvertX.ToDataTable<Item>(items3, "Text");

            
foreach (DataRow dr in dt3.Rows)
            {
                
//Console.WriteLine("{0},{1}", dr["text"].ToString(), dr[1].ToString());
                Console.WriteLine("{0}", dr["text"].ToString());
            }

            
//Test4(ToDataTable<>):Error with error column name
            try
            {
                
foreach (DataRow dr in dt.Rows)
                {
                    Console.WriteLine(dr[
"errorName"].ToString());
                }
            }
            
catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        
#endregion
    }

    
public class Item
    {
        
public Item(string text, object value)
        {
            
this.text = text;
            
this.value = value;
        }
        
private string text;
        
public string Text
        {
            
get
            {
                
return this.text;
            }
            
set
            {
                
this.text = value;
            }
        }

        
private object value;
        
public object Value
        {
            
get
            {
                
return this.value;
            }
            
set
            {
                
this.value = value;
            }
        }
    }

    public interface ITest
    
{
        
string Name get; }
        
void StartRuntime();
    }

using System;
using System.Collections.Generic;
using System.Text;
using yd.Base;
using yd.Base.Collections.Generic;
using yd.Util;

namespace ConsoleApplicationTester
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            
bool debugging = false;

            CollectionBase
<ITest> testers = new CollectionBase<ITest>();
            
//testers.Add(new QuarterTester());
            
//testers.Add(new ConvertXToDataTableTester());

            
foreach (ITest tester in testers)
            
{
                
if (debugging == false)
                
{
                    
try
                    
{
                        tester.StartRuntime();
                        Console.WriteLine(
"___________________________________");
                        Console.WriteLine(tester.Name 
+ " succeed!");
                    }

                    
catch (Exception ex)
                    
{
                        Console.WriteLine(tester.Name 
+ " with errors!");
                        Console.WriteLine(
"____________The error is under the line!__________");
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(
"!!!!!!!!!!!!!!!!!!!!@@@@@@@!!!!!!!!!!!!!!!!!!!!");
                    }

                }

                
else
                
{
                    tester.StartRuntime();
                    Console.WriteLine(
"___________________________________");
                    Console.WriteLine(tester.Name 
+ " succeed!");
                }

            }

        }

    }

}