如何合并2排序列到一个洗牌的列表,同时保持内部命令在C#序列、命令、列表

由网友(男人累女人泪)分享简介:我想一个洗牌合并后的名单将保持在列表的内部秩序。I want to a shuffled merged list that will keep the internal order of the lists.例如:列表答:11 22 33 list A: 11 22 33B组:6 7 8 有效的结果: 11月...

我想一个洗牌合并后的名单将保持在列表的内部秩序。

I want to a shuffled merged list that will keep the internal order of the lists.

例如:

列表答:11 22 33

list A: 11 22 33

B组:6 7 8

有效的结果: 11月22日 6 33 7 8

valid result: 11 22 6 33 7 8

无效结果:22 11 7 6 33 8

invalid result: 22 11 7 6 33 8

推荐答案

原来的答案:

static IEnumerable<T> MergeShuffle<T>(IEnumerable<T> lista, IEnumerable<T> listb)
{
    var first = lista.GetEnumerator();
    var second = listb.GetEnumerator();

    var rand = new Random();
    bool exhaustedA = false;
    bool exhaustedB = false;
    while (!(exhaustedA && exhaustedB))
    {
        bool found = false;
        if (!exhaustedB && (exhaustedA || rand.Next(0, 2) == 0))
        {
             exhaustedB = !(found = second.MoveNext());
            if (found)
                yield return second.Current;
        }
        if (!found && !exhaustedA)
        {
            exhaustedA = !(found = first.MoveNext());
            if (found)
                yield return first.Current;
        }
    }                
}

基于marcog的回答第二个答案

    static IEnumerable<T> MergeShuffle<T>(IEnumerable<T> lista, IEnumerable<T> listb)
    {
        int total = lista.Count() + listb.Count();
        var random = new Random();
        var indexes = Enumerable.Range(0, total-1)
                                .OrderBy(_=>random.NextDouble())
                                .Take(lista.Count())
                                .OrderBy(x=>x)
                                .ToList();

        var first = lista.GetEnumerator();
        var second = listb.GetEnumerator();

        for (int i = 0; i < total; i++)
            if (indexes.Contains(i))
            {
                first.MoveNext();
                yield return first.Current;
            }
            else
            {
                second.MoveNext();
                yield return second.Current;
            }
    }
阅读全文

相关推荐

最新文章