Asp.net 通过将Linq结果添加到数据表或数据集中来重用它
strong文本感谢Tim在另一篇帖子中为我提供了以下代码: 我在这篇新帖子中的问题是: 如何将linq结果重用或添加到数据集或数据表中,以便查询新表而不是两个单独的表?join关键字使我能够连接这两个表。现在,我想使用这个联接表来对其运行其他查询 我希望我的问题有意义。如果你需要更多信息,请告诉我Asp.net 通过将Linq结果添加到数据表或数据集中来重用它,asp.net,linq,Asp.net,Linq,strong文本感谢Tim在另一篇帖子中为我提供了以下代码: 我在这篇新帖子中的问题是: 如何将linq结果重用或添加到数据集或数据表中,以便查询新表而不是两个单独的表?join关键字使我能够连接这两个表。现在,我想使用这个联接表来对其运行其他查询 我希望我的问题有意义。如果你需要更多信息,请告诉我 DataSet ds = new DataSet("Stock"); using (var dbConnection = new OleDbConnection(connString)) using
DataSet ds = new DataSet("Stock");
using (var dbConnection = new OleDbConnection(connString))
using (var dbCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", dbConnection))
using (var da = new OleDbDataAdapter(dbCommand))
{
da.Fill(ds, "HWTypes");
}
using (var dbConnection = new OleDbConnection(stockConn))
using (var dbCommand = new OleDbCommand("SELECT * FROM [Stock_voorlopig$]", dbConnection))
using (var da = new OleDbDataAdapter(dbCommand))
{
da.Fill(ds, "Stock");
}
var joined = from rType in ds.Tables["HWTypes"].AsEnumerable()
join rStock in ds.Tables["Stock"].AsEnumerable()
on rType.Field<string>("ProductID") equals rStock.Field<string>("Partno")
select new
{
ProductID = rType.Field<string>("ProductID")
// add the other columns you need here
};
GridView1.DataSource = joined;
GridView1.DataBind();
但我得到了这个错误:
The type 'AnonymousType#1' cannot be used as type parameter 'T' in the generic type or method 'System.Data.DataTableExtensions.CopyToDataTable<T>(System.Collections.Generic.IEnumerable<T>)'. There is no implicit reference conversion from 'AnonymousType#1' to 'System.Data.DataRow'.
类型“AnonymousType#1”不能用作泛型类型或方法“System.Data.DataTableExtensions.CopyToDataTable(System.Collections.generic.IEnumerable)”中的类型参数“T”。没有从“AnonymousType#1”到“System.Data.DataRow”的隐式引用转换。
有什么帮助吗
我正在尝试这样做:
您不能“动态”创建数据表。您选择的匿名类型不是需要使用的IEnumerable
。因此,您要么使用自定义类并用持久化它所需的所有属性填充一个列表
,要么创建一个数据表
,包含所有必需的匿名类型的数据列
,并填充该列表
你看,这不是那么容易。不过,有一种动态方法。但这需要反思,因此根本没有效率
我们走吧。。。(摘录)
您可以构建自己的IEnumerable,它接受任何类型的IEnumerable(不仅仅是DataRow
),并返回一个新的DataTable
:
以下是实施(在以下人员的帮助下):
公共类ObjectShreder{
私有系统.Reflection.FieldInfo[]\u-fi;
私有系统.反射.属性信息[]\u-pi;
private System.Collections.Generic.Dictionary _ordinalMap;
私有系统。类型_类型;
//ObjectShreder构造函数。
公共对象碎纸机(){
_类型=类型(T);
_fi=_type.GetFields();
_pi=_type.GetProperties();
_ordinalMap=新字典();
}
///
///从对象序列加载数据表。
///
///要加载到数据表中的对象序列。
///输入表。表的架构必须与此匹配
///类型T。如果该表为空,则使用架构创建一个新表
///从T类型的公共属性和字段创建。
///指定如何将源序列中的值应用于
///表中的现有行。
///从源序列创建的数据表。
公共数据表分解(IEnumerable源、数据表、LoadOption?选项){
//如果T是基元类型,则从标量序列加载表。
if(类型(T).i主){
返回ShredPrimitive(源、表、选项);
}
//如果输入表为空,则创建新表。
如果(表==null){
table=新数据表(typeof(T).Name);
}
//初始化有序映射并基于类型T扩展表架构。
table=可扩展(table,typeof(T));
//枚举源序列并将对象值加载到行中。
table.BeginLoadData();
使用(IEnumerator e=source.GetEnumerator()){
while(如MoveNext()){
如果(选项!=null){
table.LoadDataRow(ShredObject(table,e.Current),(LoadOption)选项);
}否则{
table.LoadDataRow(ShredObject(table,e.Current),true);
}
}
}
table.EndLoadData();
//把桌子还给我。
返回表;
}
公共数据表ShredPrimitive(IEnumerable源、数据表、LoadOption?选项){
//如果输入表为空,则创建新表。
如果(表==null){
table=新数据表(typeof(T).Name);
}
如果(!table.Columns.Contains(“Value”)){
表.列.增加(“值”,类型(T));
}
//枚举源序列并将标量值加载到行中。
table.BeginLoadData();
使用(IEnumerator e=source.GetEnumerator()){
Object[]value=新对象[table.Columns.Count];
while(如MoveNext()){
值[表列[“值”].序号]=e.当前值;
如果(选项!=null){
表.LoadDataRow(值,(LoadOption)选项);
}否则{
table.LoadDataRow(值,true);
}
}
}
table.EndLoadData();
//把桌子还给我。
返回表;
}
公共对象[]ShredObject(数据表,T实例){
FieldInfo[]fi=\u-fi;
PropertyInfo[]pi=\u pi;
if(instance.GetType()!=typeof(T)){
//如果实例是从T派生的,则扩展表架构
//并获取属性和字段。
可扩展(表,实例.GetType());
fi=instance.GetType().GetFields();
pi=instance.GetType().GetProperties();
}
//将实例的属性和字段值添加到数组中。
Object[]value=新对象[table.Columns.Count];
foreach(fi中的字段信息f){
值[_ordinalMap[f.Name]]=f.GetValue(实例);
}
foreach(以pi表示的p属性){
值[_ordinalMap[p.Name]]=p.GetValue(实例,null);
}
//返回实例的属性和字段值。
返回值;
}
公共数据表可扩展(数据表,类型){
//如果输入表为null或值为
//在序列中,由T型派生而来。
foreach(type.GetFields()中的FieldInfo f){
如果(!_ordinalMap.ContainsKey(f.Name)){
The type 'AnonymousType#1' cannot be used as type parameter 'T' in the generic type or method 'System.Data.DataTableExtensions.CopyToDataTable<T>(System.Collections.Generic.IEnumerable<T>)'. There is no implicit reference conversion from 'AnonymousType#1' to 'System.Data.DataRow'.
private static DataTable JoinDataTablesWithLinq()
{
//rest of the code from above
return joined.CopyToDataTable();
}
public class ObjectShredder<T> {
private System.Reflection.FieldInfo[] _fi;
private System.Reflection.PropertyInfo[] _pi;
private System.Collections.Generic.Dictionary<string, int> _ordinalMap;
private System.Type _type;
// ObjectShredder constructor.
public ObjectShredder() {
_type = typeof(T);
_fi = _type.GetFields();
_pi = _type.GetProperties();
_ordinalMap = new Dictionary<string, int>();
}
/// <summary>
/// Loads a DataTable from a sequence of objects.
/// </summary>
/// <param name="source">The sequence of objects to load into the DataTable.</param>
/// <param name="table">The input table. The schema of the table must match that
/// the type T. If the table is null, a new table is created with a schema
/// created from the public properties and fields of the type T.</param>
/// <param name="options">Specifies how values from the source sequence will be applied to
/// existing rows in the table.</param>
/// <returns>A DataTable created from the source sequence.</returns>
public DataTable Shred(IEnumerable<T> source, DataTable table, LoadOption? options) {
// Load the table from the scalar sequence if T is a primitive type.
if (typeof(T).IsPrimitive) {
return ShredPrimitive(source, table, options);
}
// Create a new table if the input table is null.
if (table == null) {
table = new DataTable(typeof(T).Name);
}
// Initialize the ordinal map and extend the table schema based on type T.
table = ExtendTable(table, typeof(T));
// Enumerate the source sequence and load the object values into rows.
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 the table.
return table;
}
public DataTable ShredPrimitive(IEnumerable<T> source, DataTable table, LoadOption? options) {
// Create a new table if the input table is null.
if (table == null) {
table = new DataTable(typeof(T).Name);
}
if (!table.Columns.Contains("Value")) {
table.Columns.Add("Value", typeof(T));
}
// Enumerate the source sequence and load the scalar values into rows.
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 the table.
return table;
}
public object[] ShredObject(DataTable table, T instance) {
FieldInfo[] fi = _fi;
PropertyInfo[] pi = _pi;
if (instance.GetType() != typeof(T)) {
// If the instance is derived from T, extend the table schema
// and get the properties and fields.
ExtendTable(table, instance.GetType());
fi = instance.GetType().GetFields();
pi = instance.GetType().GetProperties();
}
// Add the property and field values of the instance to an array.
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 the property and field values of the instance.
return values;
}
public DataTable ExtendTable(DataTable table, Type type) {
// Extend the table schema if the input table was null or if the value
// in the sequence is derived from type T.
foreach (FieldInfo f in type.GetFields()) {
if (!_ordinalMap.ContainsKey(f.Name)) {
// Add the field as a column in the table if it doesn't exist
// already.
DataColumn dc = table.Columns.Contains(f.Name) ? table.Columns[f.Name]
: table.Columns.Add(f.Name, f.FieldType);
// Add the field to the ordinal map.
_ordinalMap.Add(f.Name, dc.Ordinal);
}
}
foreach (PropertyInfo p in type.GetProperties()) {
if (!_ordinalMap.ContainsKey(p.Name)) {
// Add the property as a column in the table if it doesn't exist
// already.
DataColumn dc = table.Columns.Contains(p.Name) ? table.Columns[p.Name]
: table.Columns.Add(p.Name, p.PropertyType);
// Add the property to the ordinal map.
_ordinalMap.Add(p.Name, dc.Ordinal);
}
}
// Return the table.
return table;
}
}
public static class CustomLINQtoDataSetMethods {
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);
}
}