当前位置:  开发笔记 > 前端 > 正文

LINQ2SQL到DataTable

如何解决《LINQ2SQL到DataTable》经验,为你挑选了1个好方法。

将LINQ2SQL表复制到ADO.NET DataTable的最简单方法是什么?



1> John Boker..:

这是一篇关于扩展方法的博客文章,我认为它可以做你想要的:

http://iandykes.blogspot.com/2008/05/ienumerable-to-dataset-extension-method.html

代码来自Keith Elder

/// 

/// This will take anything that implements the ICollection interface and convert

/// it to a DataSet.

/// 

/// 

/// CollectiontoDataSet converter = new CollectionToDataSet(letters);

/// DataSet ds = converter.CreateDataSet();

/// 

/// 

public class CollectionToDataSet where T : System.Collections.ICollection

{

    T _collection;

    public CollectionToDataSet(T list)

    {

        _collection = list;

    }



    private PropertyInfo[] _propertyCollection = null;

    private PropertyInfo[] PropertyCollection

    {

        get

        {

            if (_propertyCollection == null)

            {

                _propertyCollection = GetPropertyCollection();

            }

            return _propertyCollection;

        }

    }



    private PropertyInfo[] GetPropertyCollection()

    {

        if (_collection.Count > 0)

        {

            IEnumerator enumerator = _collection.GetEnumerator();

            enumerator.MoveNext();

            return enumerator.Current.GetType().GetProperties();

        }

        return null;

    }



    public DataSet CreateDataSet()

    {

        DataSet ds = new DataSet("GridDataSet");

        ds.Tables.Add(FillDataTable());

        return ds;

    }



    private DataTable FillDataTable()

    {

        IEnumerator enumerator = _collection.GetEnumerator();

        DataTable dt = CreateDataTable();

        while (enumerator.MoveNext())

        {

            dt.Rows.Add(FillDataRow(dt.NewRow(),enumerator.Current));

        }

        return dt;

    }



    private DataRow FillDataRow(DataRow dataRow, object p)

    {

        foreach (PropertyInfo property in PropertyCollection)

        {

            dataRow[property.Name.ToString()] = property.GetValue(p, null);

        }

        return dataRow;

    }



    private DataTable CreateDataTable()

    {

        DataTable dt = new DataTable("GridDataTable");

        foreach (PropertyInfo property in PropertyCollection)

        {

            dt.Columns.Add(property.Name.ToString());

        }

        return dt;

    }

}

推荐阅读
黄晓敏3023
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有