Hlavson
Hlavson

Reputation: 319

Sort list by property, but with random order of that property

I know this is little confusing, but i try to explain my problem.

public enum Manufacturer { Bmw, Ford, Volvo };

public class Car
{
    public Car(Manufacturer man, string name)
    {
        this.Man = man;
        this.Name = name;
    }

    public Manufacturer Man { get; set; }
    public string Name { get; set; }
}

//Program
private static void Main(string[] args)
{
    List<Car> myCars = new List<Car>();
    Car a = new Car(Manufacturer.Bmw, "M6");
    Car b = new Car(Manufacturer.Ford, "Focus");
    Car c = new Car(Manufacturer.Bmw, "i8");
    Car d = new Car(Manufacturer.Ford, "Mondeo");
    Car e = new Car(Manufacturer.Volvo, "XC60");
    myCars.Add(a);
    myCars.Add(b);
    myCars.Add(c);
    myCars.Add(d);
    myCars.Add(e);
    myCars = myCars.OrderBy(x => x.Man).ToList(); //Not exactly what i need
}

I want to sort my list by manufacturer property, so i do it like this.

But what i really want is, sort by manufacturer, but with random order. So sometimes BMW will be first, sometimes Fords, but all the times, cars of the same manufacturer will be next to each other.

Hope i can explained it. Thanks for help.

Upvotes: 2

Views: 164

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

Group cars by manufacturer, then sort groups in random order and select all cars from each group:

var random = new Random();
var result = myCars.GroupBy(c => c.Man)
                   .OrderBy(g => random.Next())
                   .SelectMany(g => g);

Upvotes: 1

Related Questions