Randomize list and order it by multiple in C#
Sometimes we all may want to randomize the order of the list, order it based on multiple item properties and show it in our frontend applications
LINQ queries with any IEnumerable or IEnumerable<T> collection provides lots of inbuilt functionalities to handle lists in c#. We are going to look at few of those functionalities here to achieve our target.
- Select- used to select a property from specifically for use from list
- OrderBy- used to order items by ascending based on item property
- ThenBy- used along with OrderBy to order items based on two item properties
We’ll now look how we can randomize list and order it based on multiple items
Randomize items in the list
1. Lets have small in memory list
//Lets have small in memory list
IEnumerable<BikeDTO> bikeDTOs = new List<BikeDTO>
{
new BikeDTO { BikeId=1,ReportedDate=DateTime.Now.AddDays(-1),TripCount=1,RemainingDistance=50},new BikeDTO { BikeId=2,ReportedDate=DateTime.Now.AddDays(-5),TripCount=10,RemainingDistance=10},new BikeDTO { BikeId=3,ReportedDate=DateTime.Now.AddDays(-1),TripCount=5,RemainingDistance=203},new BikeDTO { BikeId=4,ReportedDate=DateTime.Now,TripCount=1,RemainingDistance=101}
};
2. Randomize the bikeDTO list
// Randomize list
Random rnd = new Random(DateTime.Now.Millisecond);
bikeDTOs = bikeDTOs.Select(item => new { item, order = rnd.Next()})
.OrderBy(x => x.order).Select(x => x.item);
3. Order it by two properties of the item
bikeOnboardDTOs = bikeOnboardDTOs.OrderBy(x => x.BikeId).ThenBy(x => x.ReportedDate)
Note: First order it by BikeId and then by ReportedDate
Thank you for reading and I hope this is useful for beginners who starts using LINQ.