LINQ Orderby Descending Query
You need to choose a Property to sort by and pass it as a lambda expression to OrderByDescending
like:
.OrderByDescending(x => x.Delivery.SubmissionDate);
Really, though the first version of your LINQ statement should work. Is t.Delivery.SubmissionDate
actually populated with valid dates?
C# linq order by and take
Yes, very much so. It's an order of operations type thing.
Say you have a data set of
A
F
B
D
F
C
and you do a return query.Take(3).OrderBy(o => o.name);
you would get
A
B
F
However, if you do return query.OrderBy(o => o.name).Take(3);
then you would get
A
B
C
LINQ - OrderByDescending
var desc = this.SearchItems
.Where(x => x.SearchType == Foo || x.SearchType == Bar)
.OrderByDescending(i => i.ItemDisplay)
.ThenByDescending(i => i.CategoryDisplay);
var asc = this.SearchItems
.Where(x => x.SearchType != Foo && x.SearchType != Bar)
.OrderBy(i => i.ItemDisplay)
.ThenBy(i => i.CategoryDisplay);
var result = desc.Concat(asc);
Of course you can do it as one query as well.
I assume that you want the 2 descending objects first. If that's not the case then turn the last statement around.
var result = asc.Concat(desc);
If you want to sort the list itself, then do this
this.SearchItems = desc.Concat(asc).ToList();
How to write OrderByDescending and where clause in single LinQ query
You need to put parenthesis for you predicate i.e where clause.
Either use query syntax or lambda expression completely. The following should work:
(from a in Attendances
where a.Deviceid == 1
select a)
.OrderByDescending(x=>x.Id)
.Take(1)
.Select(x=>x.UpdatedDate)
or use lambda expression syntax:
Attendances.Where(a => a.Deviceid == 1)
.OrderByDescending(x=>x.Id)
.Take(1)
.Select(a => a.UpdatedDate);
Side Note:
If single item is intended to be returned, then you can use FirstOrDefault()
or First()
, you can read about the difference of both :
var latestDate = Attendances.Where(a => a.Deviceid == 1)
.OrderByDescending(x=>x.Id)
.FirstOrDefault()
?.UpdatedDate;
How to set order by descending in Linq query based on aggregated column?
Two Linq ways come to mind.
The first is using .OrderBy<T>()
followed by .Reverse<T>()
:
DataTable Dt2 = new DataTable();
Dt2 = dt.AsEnumerable()
.GroupBy(r => r.Field<string>("Vegetables"))
.Select(g =>
{
var row = dt.NewRow();
row["Vegetables"] = g.Key;
row["Pricing"] = g.Average(r => Int32.Parse(r.Field<string>("Pricing")));
return row;
})
.OrderBy(row => row["Pricing"])
.Reverse()
.CopyToDataTable();
The second is just using .OrderByDescending<T>()
:
DataTable Dt2 = new DataTable();
Dt2 = dt.AsEnumerable()
.GroupBy(r => r.Field<string>("Vegetables"))
.Select(g =>
{
var row = dt.NewRow();
row["Vegetables"] = g.Key;
row["Pricing"] = g.Average(r => Int32.Parse(r.Field<string>("Pricing")));
return row;
})
.OrderByDescending(row => row["Pricing"])
.CopyToDataTable();
If you're looking for a non-Linq solution could also apply a sorted DataView
on the DataTable
to achieve a similar result.
How to Conditionally the column in LINQ OrderByDescending for OrderBy?
You can use the library System.Linq.Dynamic.Core which supports dynamic querying, selecting and ordering.
Example code:
var q = new List<Person>
{
new Person{Name = "C", Age = 30 },
new Person{Name = "A", Age = 7 },
new Person{Name = "B", Age = 5 }
}.AsQueryable();
var x1 = q.OrderBy("Name asc");
var a1 = q.OrderBy("Age desc");
For a full working example, see dotnetfiddle
How to OrderBy ASC or DESC a specific column in LINQ according to parameters
Use Dynamic Linq
Then you can write something like this...
var field = "FirstName"; // or "LastName"
var type = "ascending"; // or "descending" <-- full
var result = (from x in db.ContactSet
select new
{
x.FirstName,
x.LastName
}).ToList();
result = result.OrderBy(field + " " + type).ToList();
How to use OrderBy in Linq
Is there any reason why I shouldn't do OrderBy always last
There may be reasons to use OrderBy
not as the last statement. For example, the sort property may not be in the result:
var result = context.Entities
.OrderBy(e => e.Date)
.Select(e => e.Name);
Or you want a sorted collection as part of the result:
var result = context.Customers
.Select(c => new
{
Customer = c,
Orders = c.Orders.OrderBy(o => o.Date)
Address = c.Address
});
Will order be faster if I order collection after one property selection?
Your examples show that you're working with LINQ to Entities, so the statements will be translated into SQL. You will notice that...
context.Entities
.OrderBy(e => e.Name)
.Select(e => e.Name)
... and ...
context.Entities
.Select(e => e.Name)
.OrderBy(s => s)
... will produce exactly the same SQL. So there is no essential difference between both OrderBy
positions.
Doesn't matter if I use Entity Framework to query a database or just querying some collection.
Well, that does matter. For example, if you do...
context.Entities
.OrderBy(e => e.Date)
.Select(e => e.Name)
.Distinct()
... you'll notice that the OrderBy
is completely ignored by EF and the order of names is unpredictable.
However, if you do ...
context.Entities
.AsEnumerable() // Continue as LINQ to objects
.OrderBy(e => e.Date)
.Select(e => e.Name)
.Distinct()
... you'll see that the sort order is preserved in the distinct result. LINQ to objects clearly has a different strategy than LINQ to Entities. OrderBy
at the end of the statement would have made both results equal.
To sum it up, I'd say that as a rule of the thumb, try to order as late as possible in a LINQ query. This will produce the most predictable results.
How to give Property Name in linq orderBy based on string Property name in C#
The second last of your examples is actually quite close to something that should work.
Ignoring everything around it the following should be a working version of the mentioned example:
// Used reflection
var convertProperty = typeof(Student).GetProperty(columnname);
students.OrderByDescending(n => convertProperty.GetValue(n).ToString() ?? string.Empty).ToListAsync();
To be fair, I haven't tried out this code, so I might have made a mistake somewhere, given this is typed freely without an IDE, but it should give a general Idea, right?
Edit
If you are using C# 6.0 and upwards you can use null checking like mentioned above, otherwise you can also use the following
students.OrderByDescending(n => (convertProperty.GetValue(n) ?? string.Empty).ToString()).ToListAsync();
Related Topics
How to Convert a Timespan to a Formatted String
How to Create Custom Config Section in App.Config
How to Programmatically Connect a Client to a Wcf Service
Getting the Folder Name from a Full Filename Path
Why Must a Lambda Expression Be Cast When Supplied as a Plain Delegate Parameter
How to Calculate Wpf Textblock Width for Its Known Font Size and Characters
Managing Multiple Selections with Mvvm
How to Reference Generic Classes and Methods in Xml Documentation
Solid Ffmpeg Wrapper for C#/.Net
The Need for Volatile Modifier in Double Checked Locking in .Net
Switch Case: How to Use a Range Instead of a One Number
.Net Core 3.0 Possible Object Cycle Was Detected Which Is Not Supported
Xml Serialize Generic List of Serializable Objects
Why Interface Layer/Abstract Classes Required in Our Project