【发布时间】:2019-05-02 23:39:39
【问题描述】:
我正在尝试对 ListView 中 JSON 中的项目进行分组。
我的 JSON 存储在 Web 存储库中,我已经从服务器中提取并列出了它,但未分组。
我已经阅读了很多关于如何对 C# 列表进行分组的教程,但没有一个能解决我的问题。
这是 JSON:
[
{
"status": "Status 1",
"erpCode": "1901",
"name": "Name 1",
"statusReportDate": "24/08/2018",
"statusReportDescription": "Description 1"
},
{
"status": "Status 2",
"erpCode": "2160",
"name": "Name 2",
"statusReportDate": "24/08/2018",
"statusReportDescription": "Description 2"
},
{
"status": "Status 2",
"erpCode": "543",
"name": "Name 3",
"statusReportDate": "24/08/2018",
"statusReportDescription": "Description 3"
}
]
我从 Web 存储库中提取 JSON 并将其转换为 List 和 ObservableCollection 的方法:
protected async void OnGetList()
{
if (CrossConnectivity.Current.IsConnected)
{
try
{
//Getting JSON data from the Web
var content = await _client.GetStringAsync(Url);
//We deserialize the JSON data from this line
var list = JsonConvert.DeserializeObject<List<Company>>(content);
//After deserializing , we store our data in the List called ObservableCollection
ObservableCollection<Company> collection = new ObservableCollection<Company>(list);
myList.ItemsSource = collection;
}
catch (Exception ey)
{
Debug.WriteLine("" + ey);
}
}
}
XAML 列表视图:
<ListView x:Name="myList"
HasUnevenRows="True"
ItemSelected="MyList_ItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal" Margin="5" HorizontalOptions="Fill">
<Button Text="{Binding erpCode}"/>
<StackLayout HorizontalOptions="Fill">
<Grid>
<Label Text="{Binding name}"/>
<Label Text="{Binding statusReportDate}"/>
</Grid>
<Label Text="{Binding statusReportDescription}"/>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我想按“状态”对其进行分组并打印如下内容:
状态 1
名字 1
状态 2
名字 2
名字 3
状态 N
名称 n1
名称 n2
名称 n3
...
【问题讨论】:
-
“他们都没有解决我的问题” - 为什么不呢?您具体尝试了什么不起作用?分组列表视图在 SO 和网络其他地方都有很好的记录。
-
我在您的代码中没有看到任何“分组操作”尝试。
-
ObservableCollection<Company> collection = new ObservableCollection<Company>(list).GroupBy(x => x.status);之类的内容应该可以帮助您入门。 -
Jason,我阅读的文档只是告诉我如何手动创建分组列表,在代码中插入所有数据,而不是像 JSON 这样从另一个列表中获取原始数据
标签: c# xaml xamarin mobile xamarin.forms