I have the following class:
class Detail
{
public Detail()
{
_details = new List<string>();
}
public IList<string> Details { get { return _details; } }
private readonly List<string> _details;
}
Currently I sort the class randomly using the following:
void ShuffleGenericList<T>(IList<T> list)
{
//generate a Random instance
var rnd = new Random();
//get the count of items in the list
var i = list.Count();
//do we have a reference type or a value type
T val = default(T);
//we will loop through the list backwards
while (i >= 1)
{
//decrement our counter
i--;
//grab the next random item from the list
var nextIndex = rnd.Next(i, list.Count());
val = list[nextIndex];
//start swapping values
list[nextIndex] = list[i];
list[i] = val;
}
}
What I would like to do is to sort the contents of details in alphabetic order.
So for example if the contents look like this:
[0] a
[1] d
[2] b
I want to be able to run this method and have them sorted into:
[0] a
[1] b
[2] d
Does anyone know of a simple way to do this? Note that the lists usually have less than ten entries in them. Can I do this with LINQ? Sorry but I am not very familiar with LINQ I have just heard a suggestion that I could use that.
Another way
_details.Sort((s1, s2) => s1.CompareTo(s2));
You should be able to use OrderBy
in LINQ...
var sortedItems = myList.OrderBy(s => s);
There are two ways:
Without LINQ: yourList.Sort();
With LINQ: yourList.OrderBy(x => x).ToList()
You will find more information in: https://www.dotnetperls.com/sort
What is wrong with List<T>.Sort()
?
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort#overloads
Source: Stackoverflow.com