c# - Avoiding code repetition when using LINQ -


Okay, I have a number of methods that look like this: - That's the artist, album, the year etc. There is a list.

  Public Zero Sorting Order (Sort Order Sort Order) {if (sort order == sort order.according) _list = _list.OrderBy (x => x.album). Ollist (); Otherwise, if (sort order == sort order removal) _list = _list.OrderByDescending (x = & gt; x.album). Ollist (); }  

and this:

  Public Zero SortByArtist (sort order sort order) {if (sort order = sort order.according) _list = _list.OrderBy (x = & Gt; X Artist). Ollist (); Else if (sortOrder == SortOrder.Descending) _list = _list.OrderByDescending (x => x.Artist) .toList (); }  

Now it is clearly not a good code, so it needs to be restructured in a sorting method, but I can not understand how to do it in the simplest way. I do not care if it uses iComparier or LINQ.

I see it like this:

  Sort public zeros (sort order order sort, sort type type sort) {/  

So what's the most obvious way to do this with a code repetition?

Thanks, Lee

You will be able to delete the signature of the OrderBy extension method

Update 1 You must first clarify your main selector in generic parameters. I am guessing on my type and it is called "songs"

  Sort Public Zero & lt; Tikey & gt; (Sort order sort order, funk lite; song, vaccine & gt; key selector) {if (sortOrder == sort order removal) {_list = _list.OrderByDescending (key selector). Olist (); } And {_list = _list.OrderBy (key selector) .Oolist (); }}  

Now you can call "sort" like this:

  sort (sort order.endending, x => x Album); After commenting Tom Lokhurst, if you want to predefine some shorthand sequence criteria, you can do this by defining:  

Update 2 < / P>

A class like this:

  Public static class sorting code {Public static reading funk & lt; Lyrics, String & gt; Artist = x = & gt; X.Artist; Funnel for public static reading & lt; Lyrics, String & gt; Album = x = & gt; X.album; }  

You can now just call:

  Sort (Sort Order, Descending, Sortclaimman Artist);  

Comments