Call method immediately after object construction in LINQ query
Posted
by Steffen
on Stack Overflow
See other posts from Stack Overflow
or by Steffen
Published on 2010-05-02T18:47:09Z
Indexed on
2010/05/02
18:58 UTC
Read the original article
Hit count: 290
c#
|linq-to-objects
I've got some objects which implement this interface:
public interface IRow
{
void Fill(DataRow dr);
}
Usually when I select something out of db, I go:
public IEnumerable<IRow> SelectSomeRows
{
DataTable table = GetTableFromDatabase();
foreach (DataRow dr in table.Rows)
{
IRow row = new MySQLRow(); // Disregard the MySQLRow type, it's not important
row.Fill(dr);
yield return row;
}
}
Now with .Net 4, I'd like to use AsParallel, and thus LINQ.
I've done some testing on it, and it speeds up things alot (IRow.Fill uses Reflection, so it's hard on the CPU)
Anyway my problem is, how do I go about creating a LINQ query, which calls Fills as part of the query, so it's properly parallelized?
For testing performance I created a constructor which took the DataRow as argument, however I'd really love to avoid this if somehow possible.
With the constructor in place, it's obviously simple enough:
public IEnumerable<IRow> SelectSomeRowsParallel
{
DataTable table = GetTableFromDatabase();
return from DataRow dr in table.Rows.AsParallel()
select new MySQLRow(dr);
}
However like I said, I'd really love to be able to just stuff my Fill method into the LINQ query, and thus not need the constructor overload.
© Stack Overflow or respective owner