>DataTable dt1 = new DataTable(); >dt1.Columns.Add("DebtorNum", typeof(Int32)); >dt1.Columns.Add("DebtorName", typeof(String)); >dt1.Columns.Add("DebtorState",typeof(String)); > >dt1.Rows.Add(1,"ABC","PA"); >dt1.Rows.Add(2,"DEF","GA"); >dt1.Rows.Add(3,"GHI","IL"); >dt1.Rows.Add(4,"JKL","IL"); >dt1.Rows.Add(5,"MNO","TX"); > >DataTable dt2 = new DataTable(); >dt2.Columns.Add("DebtorNum",typeof(Int32)); >dt2.Columns.Add("MoneyOwed",typeof(Decimal)); >dt2.Columns.Add("CaseNum",typeof(String)); > >dt2.Rows.Add(1,100,"11111"); >dt2.Rows.Add(2,200,"22222"); >dt2.Rows.Add(3,300,"33333"); >dt2.Rows.Add(3,400,"44444"); >dt2.Rows.Add(4,500,"55555"); >dt2.Rows.Add(4,600,"66666"); > >var Results = from dtDebtor1 in dt1.AsEnumerable() > where dtDebtor1.Field<string>("DebtorState") == "IL" > join dtDebtor2 in dt2.AsEnumerable() > on dtDebtor1.Field<Int32>("DebtorNum") equals dtDebtor2.Field<Int32>("DebtorNum") > select new { > DebtorNum = dtDebtor1.Field<Int32>("DebtorNum"), > DebtorName = dtDebtor1.Field<string>("DebtorName"), > MoneyOwed = dtDebtor2.Field<decimal>("MoneyOwed"), > CaseNum = dtDebtor2.Field<String>("CaseNum") > }; >>
>using System; >using System.Collections.Generic; >using System.Linq; >using System.Text; >using System.Data; >using System.Reflection; > >namespace LinqSamples >{ > public static class VarToTable > { > public static DataTable ToADOTable<T>( > this IEnumerable<T> varlist, NewRowCreateDelegate<T> fn) > { > > DataTable dtReturn = new DataTable(); > > T TopRec = varlist.ElementAt(0); > PropertyInfo[] oProps = ((Type)TopRec.GetType()).GetProperties(); > for (int i = 0; i < oProps.Length; i++) > dtReturn.Columns.Add(oProps[i].Name, oProps[i].PropertyType); > > foreach (T rec in varlist) > { > DataRow dr = dtReturn.NewRow(); > > foreach (PropertyInfo pi in oProps) > dr[pi.Name] = pi.GetValue(rec, null); > dtReturn.Rows.Add(dr); > } > > return (dtReturn); > } > public delegate object[] NewRowCreateDelegate<T>(T t); > } >} > >>
> DataTable dt = Results.ToADOTable(rec => new object[] { Results }); > dt.TableName = "MyResults"; >>