LINQ查询再次来到DataTable类型

  .NET中的LINQ对于操作集结对象提供了广大的有利,使得我们得以在C#中使用类似于SQL语句的不二秘技对聚集中的对象开展搜寻、分组、总括等。使用LINQ写出来的代码老妪能解,省去了我们原先须要选拔大批量for循环可能foreach循环本事实现的职能。有目共睹,通过LINQ查询所重返的结果平时的话是三个以var所标记的无名氏类型,该品种承袭自IEnumerable接口,大家得以一贯将它绑定到任何贰个多少绑定控件,如DropDownList,ListBox,DataGridView等。但这里有三个难题,对于DataGridView(WinForm版)来讲,假设使用LINQ重返的无名对象进行数量绑定的话,会失掉DataGridView中单击列标题进行多少排序的效益,那是因为DataGridView无法从二个无名氏对象中获得到举办数量排序的现实性准绳。要消除这些标题,你能够给那些无名氏对象编排具体的排序算法,然而最简易的做法还是将这么些无名对象调换来大家所纯熟的集聚对象,如DataTable,然后再绑定到DataGridView中。

个人以为Linq实用灵活性非常的大,参照他事他说加以考察一篇大拿的文章LINQ查询再次来到DataTable类型

  查找msdn,你能够找到将LINQ to DataSet的结果转变来DataTable的措施。下边包车型地铁代码片段来源于msdn上的牵线,

// Bind the System.Windows.Forms.DataGridView object
// to the System.Windows.Forms.BindingSource object.
dataGridView.DataSource = bindingSource;

附上自身写的二个测验程序源代码。

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

下载

DataTable orders = ds.Tables["SalesOrderHeader"];

图片 1图片 2

// Query the SalesOrderHeader table for orders placed 
// after August 8, 2001.
IEnumerable<DataRow> query =
    from order in orders.AsEnumerable()
    where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
    select order;

  //创建自定义DataTable             String[] _sFiled = new String[] { "ID", "PC", "EPC", "CRC", "RSSI", "FREQANT", "INVCOUNT" };# region Linq写法             //  LinQ写法1:             //var numbers_1 = from number in numbers where (number % 2 == 0) orderby number descending select number;//orderby number descending 这是对筛选出来的数值进行排序             //   foreach (var i in numbers_1)              //   {              //   Console.WriteLine;              //   }             //LinQ写法2:             //  var numbers_1 = numbers.Where(i => i % 2 == 0).Select(i => i);//输出用写法1一样#endregion                         DataTable    _dtAudit = CreateSelfDataTable;             _dtAudit.Rows.Add("a1", "b1", "c1","","","","");             _dtAudit.Rows.Add("a1", "b2", "c2", "", "", "", "");             _dtAudit.Rows.Add("a2", "b3", "c3", "", "", "", "");             _dtAudit.Rows.Add("a3", "b4", "c4", "", "", "", "");             _dtAudit.Rows.Add("a1", "b5", "c5", "", "", "", "");             _dtAudit.Rows.Add("a2", "b6", "c6", "", "", "", "");             var query1 = (from contact in _dtAudit.AsEnumerable()                                      //查询                           orderby contact.Field<string>("ID") descending                                      //排序                           group contact by contact.Field<string>("PC") into g                               //分组                           select new {ID=g.FirstOrDefault().Field<string>("ID"),PC=g.FirstOrDefault().Field<string>("PC"),EPC=                               g.FirstOrDefault().Field<string>("EPC"),CRC=g.FirstOrDefault().Field<string>("CRC"),RSSI=g.FirstOrDefault(                               ).Field<string>("RSSI")}).ToList();            DataTable contacts1 =ToDataTable;           SetListView(listView1, contacts1);        }        /// <summary>        /// 创建自定义列DataTable        /// </summary>        /// <param name="sList"></param>        /// <returns></returns>        public    DataTable CreateSelfDataTable(String[] sList)        {            DataTable _dtSelf = new DataTable();            foreach (String s in sList)            {                _dtSelf.Columns.Add;            }            _dtSelf.AcceptChanges();            return _dtSelf;        }          /// <summary> ///  下面通过一个方法来实现返回DataTable类型  /// LINQ返回DataTable类型/// </summary>/// <typeparam name="T"></typeparam>/// <param name="varlist"></param>/// <returns></returns>        public static DataTable ToDataTable<T>(IEnumerable<T> varlist)        {            DataTable dtReturn = new DataTable();            // column names             PropertyInfo[] oProps = null;            if (varlist == null)                return dtReturn;            foreach (T rec in varlist)            {                if (oProps == null)                {                   oProps = 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;            }            return dtReturn;        }        /// <summary>        /// 绑定ListView        /// </summary>        private void SetListView(System.Windows.Forms.ListView listView, DataTable dt)        {            if (listView.Items.Count > 50)            {                listView.Items.Clear();            }            if (dt != null && dt.Rows.Count > 0)            {                ListViewItem lv = null;                for (int i = 0; i < dt.Rows.Count; i++)                {                    lv = new ListViewItem(dt.Rows[i][0].ToString;                           //创建一列的多行对象                    lv.Tag = dt.Rows[i][0].ToString();                                         //该lv对象绑定多行一列值                    for (int j = 1; j < dt.Columns.Count; j++)                    {                        lv.SubItems.Add(dt.Rows[i][j].ToString;                             //一行添加多列的值                    }                    listView.Items.Add;                }            }        }

// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<DataRow>();

View Code

// Bind the table to a System.Windows.Forms.BindingSource object, 
// which acts as a proxy for a System.Windows.Forms.DataGridView object.
bindingSource.DataSource = boundTable;

LINQ基本语法及其示例

说明:

1、在未作其余说明的处境下,以下用到的db变量都以DataContext的实例对象,表明语法类似如下:

using (BP_DataClassesDataContext db = new BP_DataClassesDataContext(ConnectionStrings.GetInstance.Con))

{

//Code

}

2、暗中认可q为Iqueryable类型变量

简言之询问:

var q = from p in db.view_PreTestResultAuditList

select p;

简短规范查询:

格局一:直接动用where关键字

var q = from c in db.view_PrTestList

where c.FTestmanID.Equals(UserContext.CurrentUser.FID)

select c;

方式二:使用lambda 表达式

var q = db.TOriInfoAutoMemory.Where(c => c.FSampleName == sampleName);

使用 &&和|| 带代替And或Or关键字:

var entity = db.TSampleOriginalInfo.FirstOrDefault(c => c.FFromID.Equals && c.FSampleID.Equals);

like模糊条件查询:

//使用C#中的Contains关键字替代SQL中的like关键字

q = q.Where(c => c.FTaskCode.Contains(condition.Name));

In蕴含查询:

/// <param name="certificateIDs"> string[] </param>

var certi = (from c in db.TMSCertificate

where certificateIDs.ToList().Contains(c.FID.ToString

select c).ToList();

等价于:select * from TMSCertificate where FID in /* certificateIDs */

Skip和Take实现分页查询:

var q = from c in db.view_PrTestList

where c.FTestmanID.Equals(UserContext.CurrentUser.FID)

select c;

twi.data = (q.Skip(paging.startIndex).Take(paging.pageSize)).ToList();

//在那之中startIndex:跳过的不计其数中钦点的条数

// pageSize:每页显示条数

Distinct方法去除重复:

var p = (from c in dc.TSampleOriginalInfo

where sampleIDs.Contains(c.FSampleID.ToString

select new

{

c.FFromID,

c.FName

}).Distinct();

询问钦赐列使new构造集结:

var p = (from c in dc.TSampleOriginalInfo

where sampleIDs.Contains(c.FSampleID.ToString

select new

{

c.FFromID,

c.FName

}).Distinct();

join连接查询:详见下边包车型客车【join查询实例】

//此处省略……

FirstOrDefault查询知足条件的首先条记下或不设有是回到null,不发生极度:

foreach (var fromID in fromIDs)

{

var entity = db.TSampleOriginalInfo.FirstOrDefault(c => c.FFromID.Equals && c.FSampleID.Equals);

if (entity != null)

{

entities.Add;

}

}

LINQ to SQL 的最首要情势:SubmitChanges方法:

无论是你对目的做了不怎么项改成,都只是在改动内部存款和储蓄器中的别本。您未有对数据库中的实际多少做另外退换。直到你对 DataContext 显式调用 SubmitChanges方法,您所做的变动才会传导到服务器。

db.SubmitChanges();

新扩充/删除/修改后都亟待显式的调用该方法!

以下是以身作则代码

      /// <summary>        /// 添加        /// </summary>        /// <param name="varCustomer">要添加的对象</param>        /// <returns></returns>        public bool New(TTrademark idc)        {            using (CP_DataClassesDataContext db = new CP_DataClassesDataContext(GS.MODEL.ConnectionStrings.GetInstance("ZJ").Con))            {                if (idc != null)                {                    db.TTrademark.InsertOnSubmit;                    db.SubmitChanges();                    return true;                }                else                {                    return false;                }            }        }       /// <summary>       /// 新增多个【使用InsertAllOnSubmit】       /// </summary>       /// <param name="model"></param>       public void New(GS.MODEL.TItem model)       {           using (CP_DataClassesDataContext db = new CP_DataClassesDataContext(GS.MODEL.ConnectionStrings.GetInstance("ZJ").Con))           {               List<GS.MODEL.TItem> entities = new List<GS.MODEL.TItem>();               GS.MODEL.TItem entity = new GS.MODEL.TItem()               {                   FID = Guid.NewGuid(),                   FName =model.FName ,                   FParentName = model.FParentName,                   FFastCode = model.FFastCode,                   FRemark=model.FRemark,                   FSort=model.FSort               };               entities.Add;               db.TItem.InsertAllOnSubmit;               db.SubmitChanges();           }       }         /// <summary>       /// 修改       /// </summary>       /// <param name="model"></param>       public void Edit(GS.MODEL.TItem model)       {          using(CP_DataClassesDataContext db=new CP_DataClassesDataContext(GS.MODEL.ConnectionStrings.GetInstance("ZJ").Con))          {              GS.MODEL.TItem items = db.TItem.Single(c => c.FID == model.FID);              items.FName = model.FName;              items.FParentName = model.FParentName;              items.FRemark = model.FRemark;              items.FSort = model.FSort;              items.FFastCode = model.FFastCode;              db.SubmitChanges();          }       }        /// <summary>       /// 删除       /// </summary>       /// <param name="IDs"></param>       public void Delete(string[] ids)       {           using (CP_DataClassesDataContext db = new CP_DataClassesDataContext(GS.MODEL.ConnectionStrings.GetInstance("ZJ").Con))           {               List<GS.MODEL.TItem> entities = new List<GS.MODEL.TItem>();               foreach (var id in ids)               {                   var entity = db.TItem.FirstOrDefault(c => c.FID.Equals;                       if (entity != null)                       {                           entities.Add;                       }               }               db.TItem.DeleteAllOnSubmit;               db.SubmitChanges();           }       }          /// <summary>        /// 获取指定计量标准考核证书下的计量标准器/检定规程/主要配套设备        /// </summary>        /// <param name="certifiacteID"></param>        /// <returns></returns>        public IList<view_CertificateOriginalInfo> GetViewByCertificateID(Guid certifiacteID)        {            using (BPDataContext db = new BPDataContext(TCTC_ConnectionStrings.connStrJL))            {                var d = from c in db.view_CertificateOriginalInfo                        where c.FCertificateID == certifiacteID                        select c;                return d.ToList();            }        }          /// <summary>        /// 我的待检测结果任务单        /// </summary>        /// <param name="paging"></param>        /// <param name="condition"></param>        /// <returns></returns>        public TwiReturn GetMyWorkList(PagingCondition paging, ConditionModel condition)        {            TwiReturn twi = new TwiReturn();            using (BP_DataClassesDataContext db = new BP_DataClassesDataContext(ConnectionStrings.GetInstance("ZJ").Con))            {                var q = from c in db.view_PrTestList                        where c.FTestmanID.Equals(UserContext.CurrentUser.FID)                        select c;                if (condition != null)                {                    if (condition.NameSign == "TaskCode" && condition.Name != "")                    {                        q = q.Where(c => c.FTaskCode.Contains(condition.Name));                    }                    else if (condition.NameSign == "TestItemName" && condition.Name != "")                    {                        q = q.Where(c => c.FTestItemName.Contains(condition.Name));                    }                }                twi.totalCount = q.Count();                if (paging.needPaging)                {                    twi.data = (q.Skip(paging.startIndex).Take(paging.pageSize)).ToList();                }                else                {                    twi.data = q.ToList();                }                return twi;            }        }          /// <summary>        /// 选择计量标准考核证书        /// </summary>        /// <param name="sampleIDs"></param>        /// <param name="certificateIDs"></param>        public void SelectCertificate(string[] sampleIDs, string[] certificateIDs)        {            BPDataContext bpDC = new BPDataContext(TCTC_ConnectionStrings.connStrJL);            CPDataContext cpDc = new CPDataContext(TCTC_ConnectionStrings.connStrJL);            var certi = (from c in cpDc.TMSCertificate                         where certificateIDs.ToList().Contains(c.FID.ToString                         select c).ToList();            List<TSampleOriginalInfo> entities = new List<TSampleOriginalInfo>();            foreach (var sampleID in sampleIDs)            {                foreach (var c in certi)                {                    TSampleOriginalInfo entity = new TSampleOriginalInfo()                    {                        FID = Guid.NewGuid(),                        FFromID = c.FID,                        FType = 1,                        FSampleID = new Guid,                        FName = c.FCertificateName,                        FCode = c.FCode,                        FRange = c.FMeasurementRange,                        FUncertainty = c.FLevel,                        FCertificateNo = c.FCode,//c.FNumber,zjw修改                        FValidDateTo = c.FPeriodDate                    };                    entities.Add;                }            }            bpDC.TSampleOriginalInfo.InsertAllOnSubmit;            bpDC.SubmitChanges();            bpDC.Dispose();            cpDc.Dispose();        }          /// <summary>        /// 获取样品之标准/计量标准器/主要配套设备/检定规程        /// </summary>        /// <param name="sampleIDs"></param>        /// <returns></returns>        public DataTable GetBySampleIDs(List<string> sampleIDs)        {            using (BPDataContext dc = new BPDataContext(TCTC_ConnectionStrings.connStrJL))            {                var p = (from c in dc.TSampleOriginalInfo                         where sampleIDs.Contains(c.FSampleID.ToString                         select new                         {                             c.FFromID,                             c.FType,                             c.FName,                             c.FCode,                             c.FRange,                             c.FModel,                             c.FUncertainty,                             c.FCertificateNo,                             c.FValidDateTo,                             c.FManufacturer                         }).Distinct();                return LinqToDataTable.ToDataTable(p.ToList;            }        }          /// <summary>        /// 获取带检测的器具信息        /// </summary>        /// <returns></returns>        public DataTable GetBySampleName(string sampleName)        {            using (BPDataContext dc = new BPDataContext(TCTC_ConnectionStrings.connStrJL))            {                var sample = from c in dc.view_Sample_WithVCItem                           where c.FEndTag == 1 && c.FTaskEndTag == 1 && c.FOutSourcingTag == 0 && c.FAssignTag == 1 && c.FTestCompleteTag == 0 && c.FIsOuter == "否"                            select c;                var r = from s in sample                        join v in dc.view_GetSampleLeastOrginalRecord                        on s.FID equals v.FSampleID into recs                        from v in recs.DefaultIfEmpty()                        join t in dc.TTask                        on s.FTaskID equals t.FID into ts                        from t in ts                        where (sampleName == "" ? true : s.FName == sampleName) && (s.FReceiverID == UserContext.CurrentUser.FID || TCTC_ConnectionStrings.TestResultFilterByTester == "0")                        orderby s.FName, t.FCode, s.FCode                        select new                        {                            SampleID = s.FID,                            SampleCode = s.FCode,                            s.FName,                            s.FAnotherName,                            s.FTaskID,                            s.FIsRepair,                            s.FIsNeedOriginalRecord,                            s.FTestProperty,                            s.FRepairTag,                            s.VCItemID,                            s.CertiID,                            s.CertiName,                            s.TechID,                            s.TechName,                            s.TechCode,                            s.FReTestTag,                            s.FReTestFromTag,                                   v.FNumber,                            v.FFileName,                            v.FCertificateNo,                            v.FOriginalRecordID,                            v.FTag,                            TaskCode = t.FCode,                            t.FRemark,                            t.FIsUrgent,                            s.FTaskType,                            s.FTaskTypeID,                            s.FMeasurementRange,                            s.FLevel,                            s.FSigPrice                        };                DataTable dt = LinqToDataTable.ToDataTable(r.ToList;                return dt;            }        }  

  不过这几个艺术不是大家所企盼的!原因是内部的泛型类型必得是DataRow而不可能是自定义类型。如何做呢?大家可不得以将以此法子修改一下让它能支撑大肆档案的次序?

  还记得从.NET 3.0从头就提供的叁个效应吗?C#扩张方法。它同意大家向现存项目中“增多”方法,而无需创造新的派生类型、重新编写翻译或以别的艺术修改原始类型。看看msdn上的牵线,先来熟谙一下怎样是C#扩展方法吗!

  C#扩张方法是给现存项目“增多”二个措施,现存项目能够是基本数据类型(如int,string等),也足以是自定义类型。定义法规是扩展方法必得定义在一个Infiniti制命名的静态类中,该格局必须是静态方法,能够Infiniti制命名,方法的参数列表必需以this关键字起首,第二个即为要扩展的数据类型,第三个是多个变量名,相同的时间参数列表中允许定义五个别的参数以促成格局的重载。来看一个事例。

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, 
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }   
}

  静态类MyExtensions被定义在命名空间ExtensionMethods中,静态方法WordCount的参数列表中规定了该方法是对String类型的格局开展了扩张。在实质上运用中,你须要在代码中加上对ExtensionMethods命名空间的援引,然后经过String.WordCount()的法子来调用这些扩张方法。是否相当漂亮妙啊?再看一个例子。

namespace MyExtension
{
    public static class Test    {
        public static XElement ToXml(this DirectoryInfo dir)
        {
            // TO Do Something
        }
    } 
}

  下边包车型客车代码片段对DirectoryInfo类的艺术开展了扩充,将上述代码补充完整,便足以直接通过上边的方法调用新扩展的方法。

DirectoryInfo dir = new DirectoryInfo(path);
dir.ToXml();

  C#扩展方法允许对自定义的体系实行增加,同临时候允许带参数,帮忙重载。看下边包车型地铁事例。

namespace TestExtendMethod
{
    public class Student
    {
        public string Description()
        {
            return "Student.............";
        }
        public string Description(string name)
        {
            return "the student’s name is " + name;
        }
    }

    public static class Extensions
    {
        public static string TestMethod(this Student s)
        {
            return s.Description();
        }

        public static string TestMethod(this Student s, string name)
        {
            return s.Description(name);
        }
    }
}

  于是,自定义的Student类具备了带有叁个重载的TestMethod方法,该方法允许收取一个string类型的参数大概尚未参数。

  好了!回到大家的大旨上来。既然C#增加方法允许我们对项目丰盛方法,那么大家一起能够对已有的IEnumerable接口增添二个CopyToDataTable方法,使其能够将LINQ再次来到的var无名氏类型转变到DataTable。来看下具体的落到实处。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // create sequence 
            Item[] items = new Item[] { new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Jim Bob"}, 
                                        new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "John Fox"},  
                                        new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Phil Funk"},
                                        new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Eddie Jones"}};

            var query1 = from i in items
                         where i.Price > 9.99
                         orderby i.Price
                         select i;

            // load into new DataTable
            DataTable table1 = query1.CopyToDataTable();

            this.dataGridView1.DataSource = table1;
        }
    }

    public class Item
    {
        public int Id { get; set; }
        public double Price { get; set; }
        public string Genre { get; set; }
    }

    public class Book : Item
    {
        public string Author { get; set; }
    }

    public class Movie : Item
    {
        public string Director { get; set; }
    }

    public static class DataSetLinqOperators
    {
        public static DataTable CopyToDataTable<T>(this IEnumerable<T> source)
        {
            return new ObjectShredder<T>().Shred(source, null, null);
        }

        public static DataTable CopyToDataTable<T>(this IEnumerable<T> source,
                                                    DataTable table, LoadOption? options)
        {
            return new ObjectShredder<T>().Shred(source, table, options);
        }

    }

    public class ObjectShredder<T>
    {
        private FieldInfo[] _fi;
        private PropertyInfo[] _pi;
        private Dictionary<string, int> _ordinalMap;
        private Type _type;

        public ObjectShredder()
        {
            _type = typeof(T);
            _fi = _type.GetFields();
            _pi = _type.GetProperties();
            _ordinalMap = new Dictionary<string, int>();
        }

        public DataTable Shred(IEnumerable<T> source, DataTable table, LoadOption? options)
        {
            if (typeof(T).IsPrimitive)
            {
                return ShredPrimitive(source, table, options);
            }

            if (table == null)
            {
                table = new DataTable(typeof(T).Name);
            }

            // now see if need to extend datatable base on the type T + build ordinal map
            table = ExtendTable(table, typeof(T));

            table.BeginLoadData();
            using (IEnumerator<T> e = source.GetEnumerator())
            {
                while (e.MoveNext())
                {
                    if (options != null)
                    {
                        table.LoadDataRow(ShredObject(table, e.Current), (LoadOption)options);
                    }
                    else
                    {
                        table.LoadDataRow(ShredObject(table, e.Current), true);
                    }
                }
            }
            table.EndLoadData();
            return table;
        }

        public DataTable ShredPrimitive(IEnumerable<T> source, DataTable table, LoadOption? options)
        {
            if (table == null)
            {
                table = new DataTable(typeof(T).Name);
            }

            if (!table.Columns.Contains("Value"))
            {
                table.Columns.Add("Value", typeof(T));
            }

            table.BeginLoadData();
            using (IEnumerator<T> e = source.GetEnumerator())
            {
                Object[] values = new object[table.Columns.Count];
                while (e.MoveNext())
                {
                    values[table.Columns["Value"].Ordinal] = e.Current;

                    if (options != null)
                    {
                        table.LoadDataRow(values, (LoadOption)options);
                    }
                    else
                    {
                        table.LoadDataRow(values, true);
                    }
                }
            }
            table.EndLoadData();
            return table;
        }

        public DataTable ExtendTable(DataTable table, Type type)
        {
            // value is type derived from T, may need to extend table.
            foreach (FieldInfo f in type.GetFields())
            {
                if (!_ordinalMap.ContainsKey(f.Name))
                {
                    DataColumn dc = table.Columns.Contains(f.Name) ? table.Columns[f.Name]
                        : table.Columns.Add(f.Name, f.FieldType);
                    _ordinalMap.Add(f.Name, dc.Ordinal);
                }
            }
            foreach (PropertyInfo p in type.GetProperties())
            {
                if (!_ordinalMap.ContainsKey(p.Name))
                {
                    DataColumn dc = table.Columns.Contains(p.Name) ? table.Columns[p.Name]
                        : table.Columns.Add(p.Name, p.PropertyType);
                    _ordinalMap.Add(p.Name, dc.Ordinal);
                }
            }
            return table;
        }

        public object[] ShredObject(DataTable table, T instance)
        {

            FieldInfo[] fi = _fi;
            PropertyInfo[] pi = _pi;

            if (instance.GetType() != typeof(T))
            {
                ExtendTable(table, instance.GetType());
                fi = instance.GetType().GetFields();
                pi = instance.GetType().GetProperties();
            }

            Object[] values = new object[table.Columns.Count];
            foreach (FieldInfo f in fi)
            {
                values[_ordinalMap[f.Name]] = f.GetValue(instance);
            }

            foreach (PropertyInfo p in pi)
            {
                values[_ordinalMap[p.Name]] = p.GetValue(instance, null);
            }
            return values;
        }
    }
}

   Item,Book,Movie都以自定义类型,扩大方法对IEnumerable泛型接口增多了能支撑大肆档案的次序并赶回DataTable的不二秘诀CopyToDataTable,于是,我们能够一贯对LINQ重临的var无名类型应用CopyDoDataTable方法并将重返值赋值给DataTable对象。然后将DataTable直接绑定给DataGridView从而获取点击列标题实行多少排序的机能。还会有稍稍复杂一点的使用,给三个代码片段的截图。

 

图片 3

 

本文由明仕msyz手机版发布于家居装修-蜗牛装饰,转载请注明出处:LINQ查询再次来到DataTable类型

TAG标签:
Ctrl+D 将本页面保存为书签,全面了解最新资讯,方便快捷。