0

我无法根据班级中的一个属性改组列表。我的SCHEDULE课程包含两个属性:sEmployeeIDsStationID

我按如下方式填充列表,但我想ID_STATION在每次运行时随机播放并有一些不同的东西。

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));
}

实际上,我想让我的 ID_STATION 项目更改行,而我的 ID_EMPLOYEE 将保持在原来的位置。示例:由此,

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

我想要这个:

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

1 回答 1

1

这有效:

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

好的,它只有在您添加这些使用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];
        }
    }
}

功劳归于:https ://stackoverflow.com/a/1653204/284240

于 2013-07-04T22:01:54.480 回答