开发者

Create an array of arrays with Linq

开发者 https://www.devze.com 2023-01-31 02:21 出处:网络
I\'ve the following XML : <datarow> <datacol><![CDATA[Value1]]></datacol> <datacol><![CDATA[Value2]]></datacol>

I've the following XML :

<datarow>
  <datacol><![CDATA[Value1]]></datacol>
  <datacol><![CDATA[Value2]]></datacol>
  <datacol><![CDATA[Value3]]></datacol>
</datarow>
<datarow>
  <datacol><![CDATA[Value5]]></datacol>
  <datacol><![CDATA[Value6]]></dat开发者_如何学编程acol>
  <datacol><![CDATA[Value7]]></datacol>
</datarow>
// ...

How can I create an bi-dimensional array using linq?

I'll avoid doing :

foreach("datarow") {
    foreach ("datacol") { ... }
}

Thanks !

[EDIT] Final array should be like this:

array[,] = {{ "Value1", "Value2", "Value3"} , { "Value4", "Value5", "Value6"}}


Here is an example to create a jagged array from XML data.

var xmlStr = "<table><dataRow><dataCol>1</dataCol><dataCol>2</dataCol></dataRow><dataRow><dataCol>5</dataCol><dataCol>6</dataCol></dataRow></table>";
var rows = from r in XElement.Parse(xmlStr).Elements("dataRow") select r;

int[][] intJagArray = (from r in rows select (from c in r.Elements("dataCol") select Int32.Parse(c.Value)).ToArray()).ToArray();

Here's the page that helped me figure this out. http://www.daniweb.com/code/snippet267931.html


LINQ and multi-dimensional arrays do not mix well.

You can use a traditional foreach loop, but you have to calculate the size of the multi-dimensional array first:

string[,] result = new string
[
    doc.Elements("datarow").Count(),
    doc.Elements("datarow").Max(d => d.Elements("datacol").Count())
];

int x = 0;
foreach (var datarow in doc.Elements("datarow"))
{
    int y = 0;
    foreach (var datacol in datarow.Elements("datacol"))
    {
        result[x, y] = (string)datacol;
        y++;
    }
    x++;
}

But it's really much simpler to create a jagged array (i.e. a one-dimensional array of one-dimensional arrays; LINQ and one-dimensional arrays mix well!):

string[][] result = doc.Elements("datarow")
                       .Select(d => d.Elements("datacol")
                                     .Select(c => (string)c)
                                     .ToArray())
                       .ToArray();


Here is code to create Jagged Array:

        XDocument doc = XDocument.Load("...");

        string[][] data = (from row in doc.Elements("datarow")
                           select row.Elements("datacol").Select(col => col.Value).ToArray()).ToArray();

I am not sure how you can create a Multi-Dimensional Array using Linq.

0

精彩评论

暂无评论...
验证码 换一张
取 消