使用交错数组

Using jagged arrays

考虑以下代码。

public string[][] CalculateDistance(string origin, string destination)
{
        string[][] result = new string[1][];

        string url = "MyUrl"
        string requesturl = url;
        string content = fileGetContents(requesturl);
        JObject o = JObject.Parse(content);
        result[0] = new string[2];
        result[0][0] = (string)o.SelectToken("routes[0].legs[0].distance.text");
        result[0][1] = (string)o.SelectToken("routes[0].legs[0].duration.text");

        string[][] myArray = new string[2][];
        for (int i = 0; i < result.Length; i++)
        {
            string[] innerArray = result[i];
        }
        return result;
}

我正在尝试 return 一个锯齿状数组,然后在 wpf 应用程序的 ListView 上使用它。如果我在 for 循环中使用 Console.WriteLine(innerArray),我会得到正确的显示结果。但是,当显示在 ListView 中时,我得到

String[][] Array

谁能告诉我哪里出错了。我以前从未使用过锯齿状数组,所以我发现很难弄清楚我做错了什么。

XMAL 代码如下:

<ListView Name="MyList" HorizontalAlignment="Left" Height="315" Margin="1289,425,-435,0" VerticalAlignment="Top" Width="421">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Name"
                DisplayMemberBinding="{Binding Time}"
                Width="100"/>
            </GridView>
        </ListView.View>
</ListView>

以及将项目添加到我使用的列表的后端:

foreach (var items in GetAddress())
{
  MyList.Items.Add(new Distance() { Time = distance.CalculateDistance(items.FromPostCode, items.DestinationPostCode) });
}

距离Class看起来像

public class Distance
{
    public string[][] Time { get; set; }
    //More properties 
}

首先将您的列表视图更改为类似这样的内容以进行正确的数据绑定。 (使用您自己的可选长度和属性。)

<ListView x:Name="MyList" Height="299" Width="497">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Miles" Width="100" DisplayMemberBinding="{Binding Miles}"/>
            <GridViewColumn Header="Mins" Width="100" DisplayMemberBinding="{Binding Mins}"/>
        </GridView>
    </ListView.View>
</ListView>

这是使用锯齿状数组的示例。

string[][] list = new[] {new[] {"Hello", "Bye"}, new[] {"Hey", "Ho"}, new[] {"Yep", "Nope"}};
MyList.ItemsSource = list.Select(x => new {Miles = x[0], Mins = x[1]});

但我不明白您使用交错数组的原因。您已经创建了 1 个长度。那没有意义。只需使用长度为 2 的单个数组。如果您需要它来处理尚未显示的其他内容,那么您必须显示它,然后我也会更新我的答案。目前我删除了不必要的部分。

public string[] CalculateDistance(string origin, string destination)
{
    string[] result = new string[2];

    string url = "MyUrl"
    string requesturl = url;
    string content = fileGetContents(requesturl);

    JObject o = JObject.Parse(content);

    result[0] = (string)o.SelectToken("routes[0].legs[0].distance.text");
    result[1] = (string)o.SelectToken("routes[0].legs[0].duration.text");

    return result;
}

然后当你想填充项目时。请注意,您也不需要 Distance class。如果您仅将其用于绑定属性,则只需编写 new {} 即可创建匿名类型,这非常有效。

foreach (var items in GetAddress())
{
    var d = distance.CalculateDistance(items.FromPostCode, items.DestinationPostCode);
    MyList.Items.Add(new { Miles = d[0], Mins = d[1] });
}