Dynamic Linq to DataTable: Max of DateTime with GroupBy
-
Tuesday, December 11, 2012 10:56 AM
I've used the below excellent post for the basis of my dynamic linq queries
http://social.msdn.microsoft.com/Forums/is/linqprojectgeneral/thread/8f6f2352-34f6-46a4-b61f-2953417bfdfc
One thing I am having trouble with is how to perform a min/max on DateTime columns in a dyanmic linq query with groups.
e.g. The below will get the Min on a float field named Amount
var query = myDT.AsEnumerable().AsQueryable();
var newquery = query.GroupBy("new (get_item(@0).ToString() AS Column1)", "it", "Column1");
newquery = newquery.Select("new (it.Key.Tier.ToString() as Column1, @0(it) as Amount)", GetGroupByLambdaExpression(Min, "Amount", GetType(Float)));
This works fine, however if I wanted to do exactly the same on a field of Type DateTime rather than float I cannot figure out how to do it. The underlying problem is that Enumerable type doesn't have a Min method which accepts a DateTime.
Any ideas?
All Replies
-
Tuesday, December 11, 2012 11:02 AM
BF&I method is:
- convert the DateTime to a string in format "yyyy-mm-dd hh-mm-ss",
- extract the Min of that, and
- convert back to a DateTime.
"Premature optimization is the root of all evil." - Knuth
If I provoked thought, please click the green arrow
If I provoked Aha! please click Propose as Answer
We are here to learn, to share knowledge, and to earn points; all in about equal measure.
-
Tuesday, December 11, 2012 11:06 AMActually, use OrderBy and then Take 1
"Premature optimization is the root of all evil." - Knuth
If I provoked thought, please click the green arrow
If I provoked Aha! please click Propose as Answer
We are here to learn, to share knowledge, and to earn points; all in about equal measure.
-
Tuesday, December 11, 2012 11:19 AM
My first thought was to use order by however I'm dealing with groups and possibly multi-level grouping.
my query in pseudocode is something like
.Select("company as company, division as division, max(lastactivitydate)
.GroupBy("company, division")
Therefore I would need to iterate over every group then orderby and then Take 1

