Ascending/Descending in Linq - Can One Change the Order via Parameter

ascending/descending in LINQ - can one change the order via parameter?

You can easily create your own extension method on IEnumerable or IQueryable:

public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
bool descending)
{
return descending ? source.OrderByDescending(keySelector)
: source.OrderBy(keySelector);
}

public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>
(this IQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector,
bool descending)
{
return descending ? source.OrderByDescending(keySelector)
: source.OrderBy(keySelector);
}

Yes, you lose the ability to use a query expression here - but frankly I don't think you're actually benefiting from a query expression anyway in this case. Query expressions are great for complex things, but if you're only doing a single operation it's simpler to just put that one operation:

var query = dataList.OrderByWithDirection(x => x.Property, direction);

How do I specify the Linq OrderBy argument dynamically?

Here's a possiblity using reflection...

var param = "Address";    
var propertyInfo = typeof(Student).GetProperty(param);
var orderByAddress = items.OrderBy(x => propertyInfo.GetValue(x, null));

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 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

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?

LINQ query in View to order sum of amounts for category in ascending or descending order

Create Local List in Razor Page Something Like This,

@{var ListItems = (Model.MyTransactions.groupby(x => x.Category).select(item => new {
Category = item.key,
Sum = item.Sum(x => x.TransactionAmount)
}).OrderBy(e=> e.Sum).ToList();}

Use it in ForEach

@foreach (var item in ListItems)
{
<tr>
<td>@item.Category</td>
<td>@item.Sum</td>
</tr>
}

This Way you can access ListItems anywhere on page

Dynamic Order By in Linq

Well, you definitely want to use OrderByDescending instead of reversing. It's not going to be quite as brief as the SQL, but you could at least use:

IQueryable<Entity> GetSortedData(IQueryable<Entity> result, String orderby, bool desc)
{
switch (orderby.ToLowerInvariant())
{
case "id":
return desc ? result.OrderByDescending(c => c.Id) : result.OrderBy(c => c.Id);
case "code":
return desc ? result.OrderByDescending(c => c.Code) : result.OrderBy(c => c.Code);
case "active":
return desc ? result.OrderByDescending(c => c.Active) : result.OrderBy(c => c.Active);
default:
return desc ? result.OrderByDescending(c => c.Name) : result.OrderBy(c => c.Name);
}
}

You could remove that repetition with your own extension method:

public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(
this IQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector,
bool descending) =>
descending ? source.OrderByDescending(keySelector) : source.OrderBy(keySelector);

Then write:

IQueryable<Entity> GetSortedData(IQueryable<Entity> result, String orderby, bool desc)
{
switch (orderby.ToLowerInvariant())
{
case "id": return result.OrderBy(c => c.Id, desc);
case "code": return result.OrderBy(c => c.Code, desc);
case "active": return result.OrderBy(c => c.Active, desc);
default: return result.OrderBy(c => c.Name, desc);
}
}

Conditional orderby sort order in LINQ

If you build the expression incrementally you can do this. Generally easier using expressions rather than comprehension expressions:

var x = widgets.Where(w => w.Name.Contains("xyz"));
if (flag) {
x = x.OrderBy(w => w.property);
} else {
x = x.OrderByDescending(w => w.property);
}

(Assuming the Widget's property is basis of sort since you don't list one.)

LINQ OrderBy string parameter

try code:

you have directly could not used Linq Object in btu
So i have alter solution this problem.

var ds = (from btu in dc.BTUs
join zone in dc.BTUZones on btu.BTUZoneKey equals zone.BTUZoneKey
select new { btu.BTUKey, btu.Date, zone.BTUZoneName, btu.BTUValue }).ToList();

switch (e.SortExpression)
{
case : "Date":
ds= ds.OrderBy(c=>c.Date).ToList();
break;
case : "Name"
ds= ds.OrderBy(c=>c.BTUZoneName).ToList();
break;
}

and add Another Solution :

Using Linq System.Linq.Dynamic

Go to Vs studio->Tools->NewGet Package Manager->Package Manager Console

Enter Command

Install Install-Package System.Linq.Dynamic -Version 1.0.7

This Reference Add Your Project

After Using below Code:

using System.Linq.Dynamic;

string Field="";
switch (e.SortExpression)
{
case : "Date":
Field= "Date";
break;
case : "Name"
Field= "BTUZoneName";
break;
}

var ds = (from btu in dc.BTUs
join zone in dc.BTUZones on btu.BTUZoneKey equals zone.BTUZoneKey
select new { btu.BTUKey, btu.Date, zone.BTUZoneName, btu.BTUValue })
.OrderBy(Field).ToList();


Related Topics



Leave a reply



Submit