I have a table that I am writing some C# selenium automation for and need some help using Dynamic Linq. Let's say I have a basic AcctNum, AcctDate and AcctName record and each field can be sorted by the user. They could choose AcctNum (asc), AcctDate(asc) and finally AcctName (asc).
That would be:
var sortedCode = records.OrderBy(r => r.AcctNum)
.ThenBy(r => r.AcctDate)
.ThenBy(r => r.AcctName)
.ToList();
However the user could also choose AcctNum (desc), AcctDate(asc) and finally AcctName (desc).
What I would like to do is use Dynamic Linq and make each sort order a variable.
So something like:
//passed in values:
var varAcctNumOrd = "desc";
var varDateOrd = "asc";
var varAcctOrd = "desc";
var sortedCode = records.OrderBy(r => r.AcctNum, varAcctNumOrd)
.ThenBy(r => r.AcctDate, varDateOrd)
.ThenBy(r => r.AcctNum, varAcctOrd)
.ToList();
Is this possible?
If I understand correctly, the following simple custom extension methods should do the job:
public static class LinqExtensions
{
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
bool ascending)
{
return ascending ? source.OrderBy(keySelector) : source.OrderByDescending(keySelector);
}
public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(
this IOrderedEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
bool ascending)
{
return ascending ? source.ThenBy(keySelector) : source.ThenByDescending(keySelector);
}
public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(
this IQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector,
bool ascending)
{
return ascending ? source.OrderBy(keySelector) : source.OrderByDescending(keySelector);
}
public static IOrderedQueryable<TSource> ThenBy<TSource, TKey>(
this IOrderedQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector,
bool ascending)
{
return ascending ? source.ThenBy(keySelector) : source.ThenByDescending(keySelector);
}
}
And the usage will be:
//passed in values:
var varAcctNumOrd = "desc";
var varDateOrd = "asc";
var varAcctOrd = "desc";
var sortedCode = records.OrderBy(r => r.AcctNum, varAcctNumOrd != "desc")
.ThenBy(r => r.AcctDate, varDateOrd != "desc")
.ThenBy(r => r.AcctNum, varAcctOrd != "desc")
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With