How can I convert a list<> to a multi-dimensional array?

后端 未结 4 1729
梦如初夏
梦如初夏 2020-12-17 03:36

I have the following method signature:

public void MyFunction(Object[,] obj)

I create this object:

List&         


        
4条回答
  •  悲哀的现实
    2020-12-17 04:22

    Here is a solution using Linq's Aggregate extension.

    Note that the below does not check, nor is concerned if it gets a jagged sub list, it uses the max size of all the sublists and fills in according to the current list. If that is a concern one could add a check to the if to check for the same count amongst all the sub lists.

    public static T[,] To2DArray(this List> lst)
    {
    
        if ((lst == null) || (lst.Any (subList => subList.Any() == false)))
            throw new ArgumentException("Input list is not properly formatted with valid data");
    
        int index = 0;
        int subindex;
    
        return 
    
           lst.Aggregate(new T[lst.Count(), lst.Max (sub => sub.Count())],
                         (array, subList) => 
                            { 
                               subindex = 0;
                               subList.ForEach(itm => array[index, subindex++] = itm);
                               ++index;
                               return array;
                             } );
    }
    

    Test / Usage

    var lst = new List>() { new List() { "Alpha", "Beta", "Gamma" },
                                         new List() { "One", "Two", "Three" },
                                         new List() { "A" }
                                     };
    var newArray = lst.To2DArray();
    

    Result:

提交回复
热议问题