MiBol
MiBol

Reputation: 2125

Using LINQ to convert array object[,] to array

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

SAP data

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 ERROR

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?

Upvotes: 1

Views: 1374

Answers (3)

MiBol
MiBol

Reputation: 2125

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();

Result

Upvotes: 0

Rufus L
Rufus L

Reputation: 37060

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

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

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).

Upvotes: 5

Related Questions