0

I am having trouble shuffling a list based on one property in my class. My SCHEDULE class contains two properties: sEmployeeID and sStationID

I populate the list as follows, but I would like to shuffle by ID_STATION and have something different at every run.

List<SCHEDULE> scheduleList = new List<SCHEDULE>();

foreach (DataRow row2 in tschedule.Rows)
{
    sEmployeeID = row2["ID_EMPLOYEE"].ToString();
    sStationID = row2["ID_STATION"].ToString();
    scheduleList.Add(new SCHEDULE(sEmployeeID, sStationID));
}

Actually I would like to get my ID_STATION items change rows while my ID_EMPLOYEEs will stay at their original positions. Example: From this,

ID_EMPLOYEE         ID_STATION
ALAD                     DECH
FRED                     DECI
MIKE                     ORR
PAM                      OR
RAK                      ORW
RAYN                     PROC

I would like to have this:

ID_EMPLOYEE         ID_STATION
ALAD                     ORW
FRED                     PROC
MIKE                     DECI
PAM                      DECH
RAK                      OR
RAYN                     ORR
Yandroide
  • 91
  • 1
  • 4
  • 13

1 Answers1

1

This works:

scheduleList = scheduleList.Shuffle().ToList();

Ok, it works only if you add these extensions which uses the Fisher-Yates-Durstenfeld shuffle:

public static class EnumerableExtensions
{
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
    {
        return source.Shuffle(new Random());
    }

    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (rng == null) throw new ArgumentNullException("rng");

        return source.ShuffleIterator(rng);
    }

    private static IEnumerable<T> ShuffleIterator<T>(
        this IEnumerable<T> source, Random rng)
    {
        List<T> buffer = source.ToList();
        for (int i = 0; i < buffer.Count; i++)
        {
            int j = rng.Next(i, buffer.Count);
            yield return buffer[j];

            buffer[j] = buffer[i];
        }
    }
}

The credit goes to: https://stackoverflow.com/a/1653204/284240

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Hi Tim Schmelter, Your code works fine but this is not the result I was expecting. I will probably use it for something else though. Thanks a lot. – Yandroide Jul 05 '13 at 02:04
  • Hey @Tim Schmelter, I tried to implement your code in a different way and the result is now close to what I wanted. I just don't want the shuffle to repeat items in `ID_STATION`. how can I modify your code to get a unique `ID_STATION`? – Yandroide Jul 05 '13 at 16:30