I want to write a generic method with the following signature :
IList<T> Sort<T> (IList<T> list) where T: IComparable <T>
that returns a sorted list.
sorry for the incomplete original post.
so I want to sort the list and then select the first n elements
that would be
List<T> temp = new List<T>(list);
temp.Sort();
List<T> temp2 = new List<T>(temp);
temp2.Take(count);
the complete question would be how to do that without double – copying the initial list.
there would be 2 cases :
the list has dupes and I want to retrieve the first n distinct values
the list has dupes and I want to retrieve the first n values.
for the first case a distinct should be applied also – so a new “third “copy of list to be avoided.
of course the answer posted by guffa is accepted, because the OP at first was incomplete.
Create a new
List<T>from the input and sort it:The
Sortmethod will use the default comparer when you don’t specify one, which uses theIComparable<T>implementation if there is one.Edit:
To answer the edited question:
You have to copy the list twice if you want to preserve the input and return a list.
You could get around the second copying if you return
IEnumerable<T>instead ofIList<T>. Then you can return a deferred result that reads from the first copy of the list. The drawback is of course that it will keep the entire first list in memory although you only use a part of it.Anyway, the version returning an
IList<T>would be something like:For the version returning an
IEnumerable<T>you would just not do the.ToList()in the last step.