Repeat list endlessly (Zip a finite list with an Infinite repeating sequence)

前端 未结 2 1796
眼角桃花
眼角桃花 2021-01-14 03:13

UserList is a list of dictionaries, like:

[
  {Name:\"Alex\",Age:25},
  {Name:\"Peter\",Age:35},
  {Name:\"Muhammad\",Age:28},
  {Name:\"Raul\",         


        
相关标签:
2条回答
  • 2021-01-14 03:51

    Something like this should do the trick:

    var i = 0;
    var l = RowColorList.Count;
    UserList.ForEach(user => user.Add("RowColor", RowColorList[(i++) % l]));
    

    The % operator will guarantee "cyclic" access to the RowColorList.

    0 讨论(0)
  • 2021-01-14 04:00

    You can create a function to return an infinite enumerable of Color / string (or whatever the type of RowColor is), by using yield return as a lazy generator:

    public IEnumerable<Color> InfiniteColors()
    {
        while (true)
        {   
            foreach (var color in RowColors)
            {
                yield return color;
            }
        }
    }
    

    This can then be used with any of the Linq IEnumerable extension methods such as Zip.

    UserList.Zip(InfiniteColors(),(user,color) => user.Add("RowColor",color))
    

    Edit - Explanation

    The reason why InfiniteColors doesn't hang is because the state machine will yield back to the caller after each result, and Zip will terminate on the first enumerable to complete, which is because the other collection being zipped is finite (i.e. UserList)

    Obviously you shouldn't try and Zip the InfiniteColors enumerable with itself, nor should you try and materialize InfiniteColors, i.e. don't call InfiniteColors.ToList() or such :-):

    0 讨论(0)
提交回复
热议问题