0

I am trying to split a concurentBag in 2D list of specific length.

Current code I am using. Here the bag can be of any length between 1 - 1000.

 private static readonly ConcurrentBag<object> bag = new();

    public static void updateResult()
    {
        var i = bag.GetEnumerator();
        var tempL = 100;
        List<List<object>> data = new();
        List<object> temp = new();
        while (i.MoveNext()) {
            tempL -= 1;
            if (tempL > 0)
            {
                temp.Add(i.Current);
            }
            else
            {
                data.Add(temp);
                temp.Clear();
                tempL = 100;
            }
        }
        if(temp.Count > 0)
        {
            data.Add(temp);
        }
}

Hoping to optimize the code or any inbuilt method that can replace this messy code

Rohit Pratap
  • 365
  • 2
  • 8

1 Answers1

1

you could use Enumerable.Chunk if you are using .Net 6, otherwise it is not very difficult to write.

List<object[]> chunks = bag.Chunk(100).ToList();

Hoping to optimize the code

Optimize for what? Runtime? Readability?

Note that this produces a jagged array/list. If you want to represent a 2D grid you are better of using a multidimensional array object[,] or create your own wrapper around a 1D array that trivializes the problem:

public class My2DArray<T>{
    public T[] Data {get; }
    public int Width { get; }
    public int Height { get; } // this could be derived from the width & array length
    public T this[int x, int y]
        {
            get => Data[y * Width + x];
            set => Data[y * Width + x] = value;
        }
}

Note that this makes no difference if the source is a ConcurrentBag or a IEnumerable. If the concurrentBag changes concurrently with this code, values might or might not be included.

JonasH
  • 28,608
  • 2
  • 10
  • 23
  • The reason I asked what version of .NET was to check if `Chunk` was available since it was only introduced in .NET 6. Definitely worth being a little cautious before adding answers like this without knowing beforehand. – DavidG Dec 09 '22 at 12:45
  • @DavidG Fair point, I added a link to "how do I chunk an enumerable?" – JonasH Dec 09 '22 at 13:00