1

I want to use Linq to select and group DataTable rows... and I want to order those in a descending manner by the "Max" created date in each group... are there any improvements that could be made to this code, in particular can I make the OrderByDescending part of the Linq, for example using:

                    orderby {... something here...} descending

--- current code ---

        DataTable dt = ReadDataTable();
        var rows = (from row in dt.AsEnumerable()
                    where row.Field<bool>("Active") == true
                    group row by new
                    {
                        CollectionId = row.Field<int>("CollectionId"),
                        CollectionName = row.Field<string>("CollectionName"),
                    } into grp
                    select new
                    {
                        CollectionId = grp.Key.CollectionId,
                        CollectionName = grp.Key.CollectionName,
                        MaxCreated = grp.Max(r => r.Field<DateTime>("Created"))
                    }).OrderByDescending(r => r.MaxCreated);
1

1 Answer 1

2

You can use the let clause to hold intermediate results in a complex LINQ query, for use in subsequent sorts and selects. In your case you can use it to store the final result for subsequent sorting.

I.e. you can rewrite your Linq without the OrderByDescending() lambda as follows:

DataTable dt = ReadDataTable();
var rows = from row in dt.AsEnumerable()
           where row.Field<bool>("Active")
           group row by new
           {
               CollectionId = row.Field<int>("CollectionId"),
               CollectionName = row.Field<string>("CollectionName"),
           } into grp
           let result = new
           {
               CollectionId = grp.Key.CollectionId,
               CollectionName = grp.Key.CollectionName,
               MaxCreated = grp.Max(r => r.Field<DateTime>("Created")),
           }
           orderby result.MaxCreated descending
           select result;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.