简体   繁体   English

在 C# 中将 concurrentbag 拆分为 2D 列表

[英]Split concurrentbag to 2D list in C#

I am trying to split a concurentBag in 2D list of specific length.我正在尝试在特定长度的二维列表中拆分一个 concurentBag。

Current code I am using.我正在使用的当前代码。 Here the bag can be of any length between 1 - 1000.这里的袋子可以是 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希望优化代码或任何可以替换此混乱代码的内置方法

you could use Enumerable.Chunk if you are using.Net 6, otherwise it is not very difficult to write .如果你使用.Net 6,你可以使用Enumerable.Chunk ,否则写起来不是很困难

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:如果你想表示一个二维网格,你最好使用多维数组object[,]或围绕一维数组创建你自己的包装器来解决问题:

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 .请注意,如果源是ConcurrentBagIEnumerable ,这没有区别。 If the concurrentBag changes concurrently with this code, values might or might not be included.如果 concurrentBag 与此代码同时更改,则可能包含也可能不包含值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM