score:12
you should be able to mimick the signature of the orderby extension method:
update 1 you have to be explicit in the first generic parameter to your keyselector func. i'm going to take a guess at your type and call it "song".
public void sort<tkey>(sortorder sortorder,
func<song, tkey> keyselector)
{
if (sortorder == sortorder.descending)
{
_list = _list.orderbydescending(keyselector).tolist();
}
else
{
_list = _list.orderby(keyselector).tolist();
}
}
now you can call "sort" like this:
sort(sortorder.descending, x => x.album);
update 2
following up on tom lokhorst's comment: if you want to predefine some shorthand sort criteria, you could do so by defining a class like this:
public static class sortcolumn
{
public static readonly func<song, string> artist = x => x.artist;
public static readonly func<song, string> album = x => x.album;
}
now you can simply call:
sort(sortorder.descending, sortcolumn.artist);
score:-1
sounds like sorting is taking on a life of its own if you have several methods dedicated to it. maybe they can be gathered into a class.
public enum sortorder
{
ascending = 0,
descending = 1
}
public class sorter<t>
{
public sortorder direction { get; set; }
public func<t, object> target { get; set; }
public sorter<t> nextsort { get; set; }
public iorderedenumerable<t> applysorting(ienumerable<t> source)
{
iorderedenumerable<t> result = direction == sortorder.descending ?
source.orderbydescending(target) :
source.orderby(target);
if (nextsort != null)
{
result = nextsort.applynextsorting(result);
}
return result;
}
private iorderedenumerable<t> applynextsorting
(iorderedenumerable<t> source)
{
iorderedenumerable<t> result = direction == sortorder.descending ?
source.thenbydescending(target) :
source.thenby(target);
return result;
}
}
here's sample usage:
list<string> source = new list<string>()
{ "john", "paul", "george", "ringo" };
sorter<string> mysorter = new sorter<string>()
{
target = s => s.length,
nextsort = new sorter<string>()
{
direction = sortorder.descending,
target = s => s
}
};
foreach (string s in mysorter.applysorting(source))
{
console.writeline(s);
}
output is paul, john, ringo, george.
score:0
i think you should add an extension method to ilist<t>
:
public static class extilist {
public static ilist<t> sort<t, tkey>(this ilist<t> list, sortorder sortorder, func<t, tkey> keyselector) {
if (sortorder == sortorder.descending) {
return list.orderbydescending(keyselector).tolist();
} else {
return list.orderby(keyselector).tolist();
}
}
}
and then you can use pretty with every your objects:
ilist<person> list = new list<person>();
list.add(new person("david","beckham"));
list.add(new person("gennaro","gattuso"));
list.add(new person("cristian","carlesso"));
list = list.sort(sortorder.descending, x => x.name);
ps sortorder already exists:
using system.data.sqlclient;
score:2
you might try using a generic comparer.
Source: stackoverflow.com
Related Query
- Avoiding code repetition when using LINQ
- How to reuse a linq expression for 'Where' when using multiple source tables
- Linq sub query when using a repository pattern with EF code first
- How can I check the number of calls to the database in LINQ query when using .NET Core and Code First?
- Updating List using LINQ working when execute from Immediate window, not from code direct
- Getting InvalidCastException when trying to implement sorting in Entity Framework Code First using Linq
- Convert string[] to int[] in one line of code using LINQ
- Entity-framework code is slow when using Include() many times
- Ambiguous call when using LINQ extension method on DbSet<T>
- How to handle nulls in LINQ when using Min or Max?
- How to avoid Query Plan re-compilation when using IEnumerable.Contains in Entity Framework LINQ queries?
- Why does this Linq Cast Fail when using ToList?
- Why does C# compiler create private DisplayClass when using LINQ method Any() and how can I avoid it?
- What actually happens when using async/await inside a LINQ statement?
- Differences between IEquatable<T>, IEqualityComparer<T>, and overriding .Equals() when using LINQ on a custom object collection?
- Performance concern when using LINQ "everywhere"?
- Why do I have to copy "this" when using LINQ in a struct (and is it OK if I do)?
- linq deferred execution when using locks in methods that return IEnumerable
- How does LINQ defer execution when in a using statement
- Exception when using LINQ SUM
- Why is this LINQ query not executed when using foreach?
- Is ToList required when using foreach with LINQ to Entities
- Reference required error only when using LINQ
- LINQ isn't calling Dispose on my IEnumerator when using Union and Select, expected behavior or bug?
- Entity Framework Linq Query to List - Error when using contains: Only primitive types, enumeration types and entity types are supported
- When using a LINQ Where clause on a Dictionary, how can I return a dictionary of the same type?
- Why is IQueryable twice as fast than IEnumerable when using Linq To Objects
- Left outer join using LINQ -- understanding the code
- Good way to time SQL queries when using Linq to SQL
- Using LINQ to delete an element from a ObservableCollection Source
More Query from same tag
- Call Stored Procedure on specific database with MVC Application connecting to 2 databases
- Hierarchical queries in LINQ
- LINQ query null exception when Where returns 0 rows
- Select Distinct Row from Data Table with Dynamic Columns
- Entity Framework, eager loading entites
- Select the max,min of nested lists vb.net
- Writing a method to be used as IQueryable
- LinqtoSQL Getting a value from another table
- C# Linq get values from column B if column A matches
- Does LINQ have an equivilant of @@IDENTITY or SCOPE_IDENTITY()?
- LINQ to SQL displayed in console mode app
- Calculate Player WinLoss Percentage
- Extracting the value from a Member Expression that contains a parameter
- Construct AndAlso/OrElse LINQ expression with custom method
- Convert Function Based on TSQL with Function Based with Entity Framework
- How to write SQL procedure to insert multiple items at a time from the list?
- Condition merge while merging duplicate of two List
- convert object list to type array and remove null values
- Join with count and multiple conditions - LINQ C#
- Join to return multiple columns and using group by Entity Framework
- How to avoid if else statements in filter API in Linq
- "Runtime errors might occur when converting 'system.linq.IQueryable(of String)' to 'String'
- Get Entity From Table Using Reflection From Abstract Type
- Help me understand NewExpression.Members
- Unified SQL getter with LINQ
- How do I LINQify this?
- How to search for FirstName + Lastname from sql data base when input is full name with entities in c#?
- Is there an equivalent in LINQ for the SQL Server PARTITION OVER functionality?
- Equivalent LINQ statement to SQL statement
- following linq performing left outer join instead of inner join