-2

I dont really understand about linq, can you help me with this query?

 SELECT   *
  FROM   attachment
 WHERE   create_date IN (  SELECT   MAX (create_date)
                             FROM   attachment
                         GROUP BY   document_id, attachment_type)

how can I change it to linq statement. I'm using DataTable.

sorry, I have DataTable that have field attachment_id, document_id, attachment_type and create_date. And I really can't use dt.Select() :(

and also I need to change it back to DataTable or Datarow

0

1 Answer 1

1

Although your question is not really clear, i assume that this is what you're looking for:

var orderedDocGroups = tbl.AsEnumerable()
.GroupBy(r => new
{
    DocID = r.Field<int>("document_id"),
    AttID = r.Field<int>("attachment_type"),
})
.Select(group => new{
    DocID = group.Key.DocID,
    AttID = group.Key.AttID,
    MaxCreationDateRow = group
        .OrderByDescending(r => r.Field<DateTime>("create_date"))
        .First()
}).OrderByDescending(x => x.MaxCreationDateRow.Field<DateTime>("create_date"));

foreach(var docGroup in orderedDocGroups)
{
    var docInfo = string.Join(", ", string.Format("document_id:{0} attachment_type:{1} create_date:{2}",
                    docGroup.DocID, docGroup.AttID, docGroup.MaxCreationDateRow.Field<DateTime>("create_date")));
    Console.WriteLine(docInfo);
}

How can I change it back to datarow?

// convert back to a DataTable only with the rows with max creationdate per group:
DataTable tblMaxCreationDate = orderedDocGroups
    .Select(g => g.MaxCreationDateRow)
    .CopyToDataTable();

Here's sample code to test the above:

var tbl = new DataTable();
tbl.Columns.Add("attachment_id",typeof(Int32));
tbl.Columns.Add("document_id",typeof(Int32));
tbl.Columns.Add("attachment_type",typeof(Int32));
tbl.Columns.Add("create_date",typeof(DateTime));

var rnd = new Random();
for(int i=0; i < 10; i++)
{
    tbl.Rows.Add(i, rnd.Next(1, 5), rnd.Next(1, 3), new DateTime(2012, 07, 24, rnd.Next(1, 24), 0, 0));
}
4
  • Thanks for the answer. I'm trying to understand it to my code :) Jul 24, 2012 at 8:21
  • @Mr.Rendezvous: Edited my answer since i assume that you want the max creation date row of each group. Jul 24, 2012 at 8:51
  • I'm sorry, how can I change it back to datarow? @Tim Jul 25, 2012 at 1:51
  • @Mr.Rendezvous: Edited my answer to show hwo to convert it to an DataTable only with the MaxRows. Jul 25, 2012 at 7:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.