Home > other >  Split concurrentbag to 2D list in C#
Split concurrentbag to 2D list in C#

Time:12-10

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

CodePudding user response:

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.

  •  Tags:  
  • c#
  • Related