Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Transformations on returned data set
Message
 
 
To
09/05/2013 18:07:47
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Environment versions
Environment:
C# 4.0
OS:
Windows 7
Network:
Windows 2003 Server
Database:
MS SQL Server
Miscellaneous
Thread ID:
01573095
Message ID:
01573336
Views:
45
>>So is there a reason you didn't create a new table an manually loop through the rows? You are trying to force LINQ to do something it wasn't designed to do (create a new DataTable with a different structure). If you need the results as a DataTable, it needs to have a structure defined so that DataRows can be created for it. If you don't want to do that, you could write a method that would convert an IEnumberable< object> to a DataTable. Or you could create a class to hold the results of your query and use that instead of a DataTable to pass the results to the other function.
>
>Here is an IEnumerable to DataTable extension method for anyone interested:
>
>public static DataTable ToDataTable<T>(this IEnumerable<T> source) where T : class
>{
>	DataTable retVal = new DataTable();
>
>	var props = typeof(T).GetProperties().ToList();
>
>	retVal.Columns.AddRange(props.AsParallel()
>		.Select(prop => new DataColumn(prop.Name, (Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType)))
>		.ToArray());
>
>	foreach (var obj in source)
>	{
>		var newRow = retVal.NewRow();
>		foreach (var prop in props)
>		{
>			newRow.SetField(prop.Name, prop.GetValue(obj, null));
>		}
>		retVal.Rows.Add(newRow);
>	}
>
>	retVal.AcceptChanges();
>
>	return retVal;
>}
>
Thanks, Rob.
If it's not broken, fix it until it is.


My Blog
Previous
Reply
Map
View

Click here to load this message in the networking platform