There are a lot of things worth learning about in LINQ. Here we will mainly introduce LINQ to able, including the datatable type and other aspects.
LINQ to able
The difficulty of query is no longer felt by LINQ, which makes it easy for us to implement difficult queries. Maybe the remaining question may be a very simple question: how to save these query results?
- VaR _ result = Dal. Utility. selectall<Customer>();
- VaR _ filter =
- From Q in _ result
- Where Q. customerid. startswith ("B ")
- Select New
- {
- Q. customerid,
- Q. contactname,
- Q. companyName
- };
_ Result is the result of searching all customers. _ filter is the {customerid, contactname, companyName} set of customerid starting with "B" in _ result, however, this anonymous type cannot be returned to another method as a variable.
This {customerid, contactname, companyName} collection may be reflected to a able type, which is more suitable for general database requirements. It may also be a solution for some old systems to easily plug in the wings of LINQ.
The following shows the method for writing data to a LINQ able (which is the same in some sense ):
- Public static system. Data. datatable linqtodatatable<T>(Ienumerable<T>Data)
-
- {
-
- VaR dt = new system. Data. datatable ();
-
- VaR PS = typeof (T). getproperties (). tolist ();
-
- PS. foreach (P =>DT. Columns. Add (P. Name, P. propertytype ));
-
-
-
- Foreach (t in data)
-
- {
-
- VaR DR = DT. newrow ();
-
- VaR Vs = from P in PS select P. getvalue (T, null );
-
- VaR ls = vs. tolist ();
-
- Int I = 0;
-
- Ls. foreach (C =>Dr [I ++] = C );
-
- DT. Rows. Add (DR );
-
- }
-
- Return DT;
-
- }
-
-
- Public static system. Data. datatable todatatable<T>(Ienumerable<T>Data)
-
- {
-
- VaR dt = new system. Data. datatable ();
-
- VaR PS = system. componentmodel. typedescriptor. getproperties (typeof (t ));
-
- Foreach (system. componentmodel. propertydescriptor DP in PS)
-
- DT. Columns. Add (DP. Name, DP. propertytype );
-
- Foreach (t in data)
-
- {
-
- VaR DR = DT. newrow ();
-
- Foreach (system. componentmodel. propertydescriptor DP in PS)
-
- Dr [DP. Name] = DP. getvalue (t );
-
- DT. Rows. Add (DR );
-
- }
-
- Return DT;
-
- }