简体   繁体   中英

Using LINQ to convert array object[,] to array

I have information from external system that always return to me in the following format:

SAP数据

I am required to convert this information from object[,] to an Array split on "|". I'm been using LINQ in VB to get this information:

Dim vSAPdataTemp(,) As Object = Local_SAPtableData.Data

Dim vLinq = From TempResult In vSAPdataTemp
            Select Value = Array.ConvertAll(TempResult.ToString.Split(RFC_DelimiterChar),
                                    Function(vVal) CObj(vVal.ToString.Trim))

Dim vNewSAPdata() As Object = vLinq.ToArray

But now I'm moving to C# and I'm stuck with the following error:

LINQ错误

When using this code:

var vSAPdataTemp = Local_SAPtableData.Data;

Local_SAPtableData.FreeTable();
fw.gcCleaner();
Local_SAPtableData = null;

var vLinq = (from TempResult in (vSAPdataTemp as Object[,])
                       select string strValue = Array.ConvertAll(TempResult.Split(stcVariables.strSapRfcDelimiterChar), 
                           vVal => (vVal as object).ToString().Trim()));

var vNewSAPdata = vLinq.ToArray<string>();

What (if any) workaround exists for this issue?

You most likely have to use Cast call:

from TempResult in (vSAPdataTemp as object[,]).Cast<object>()
(...)

That's because object[,] implements non-generic IEnumerable which doesn't work well with LINQ. (I have no clue why it works in VB.NET to begin with).

Can you do something like this?

var items = new List<string>();

foreach (var vSAPdata in vSAPdataTemp)
{
    items.AddRange(vSAPdata.ToString().Split('|'));
}

Update

Testing done with 5 million records...

var maxElements = 5000000;
var vSAPdataTemp = new Object[maxElements, 1];

for (int i = 0; i < maxElements; i++)
{
    vSAPdataTemp[i, 0] = string.Format("{0}first|{0}second|{0}third", i);
}

var items = new List<string>();

var sw = new Stopwatch();
sw.Start();

foreach (var vSAPdata in vSAPdataTemp)
{
    items.AddRange(vSAPdata.ToString().Split('|'));
}

sw.Stop();
Console.WriteLine("Elapsed: {0}", sw.Elapsed);

Result:

Elapsed: 00:00:06.25855573

Thanks to @MarcinJuraszek for the answer to my problem. I only want to post the resolution of my specific case:

var vSAPdataTemp = Local_SAPtableData.Data;

string[][] vLinq = (vSAPdataTemp as Object[,]).Cast<string>()
                .Select(str => str.Split(stcVariables.strSapRfcDelimiterChar)
                .Select(stra => stra.Trim()).ToArray()).ToArray();

结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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