簡體   English   中英

將二維對象數組轉換為自定義類型列表的快速方法

[英]Fast way to convert a two dimensional object array to a List of custom type

我有一個二維對象數組,如下所示:

object[,] twoDimensionalArray = new object[,] 
{ 
    new object[] {"columnHeader1", 1, 2, 3},
    new object[] {"columnHeader2", 4, 5, 6},
    new object[] {"columnHeader3", 7, 8, 9}
};

假設我有一個如下課程:

public class MyCustomObject
{
    public string ColumnHeader{get;set;}
    public int ValueOne{get;set;}
    public int ValueTwo{get;set;}
    public int ValueThree{get;set;}
}

知道我可能正在處理可能包含一百個列的成千上萬的行,將我的twoDimensionalArray變量映射到List的最快,最有效的方法是什么?

有明顯的for循環,但我猜有更好的方法。

謝謝閱讀。

好吧,您正在尋求最快,最有效的方法。

好的ol'for循環是最快的。 毫無疑問。 但是仍然應該使用真實數據進行測量。

兩種選擇:

    object[,] array = new object[,] 
        { 
            {"columnHeader1", 1, 2, 3},
            {"columnHeader2", 4, 5, 6},
            {"columnHeader3", 7, 8, 9}
        };

    int i, maxI = array.GetLength(0);

    List<MyCustomObject> output = new List<MyCustomObject>();

    // 1 - plain old for        
    for(i = 0; i < maxI; i++) {
        var obj = new MyCustomObject {
            ColumnHeader = (string)array[i,0],
            ValueOne = (int)array[i,1],
            ValueTwo = (int)array[i,2],
            ValueThree = (int)array[i,3]
        };
        output.Add(obj);
    }

    Console.WriteLine(output[0].ColumnHeader);
    Console.WriteLine(output[2].ValueThree);

    // 2 - just the same, with Linq. If you need streaming,
    //     linq lets you return the IEnumerable so you can
    //     do foreach on it
    output = Enumerable.Range(0, array.GetLength(0))
        .Select(idx => new MyCustomObject {
                ColumnHeader = (string)array[idx,0],
                ValueOne = (int)array[idx,1],
                ValueTwo = (int)array[idx,2],
                ValueThree = (int)array[idx,3]
            }).ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM