我正在使用Xamarin.forms进行跨平台应用程序,我需要从MySql Server检索数据。通过我的研究,我发现使用MySqlClient库是不安全的,所以我在我的数据库和应用程序之间使用Web服务层进行搜索。
此代码使查询到MySql数据库,在数组中输出结果并以JSON编码回显它们。这是PHP代码:
<?php
$servername = "adress";
$username = "client";
$password = "";
$dbname = "dnName";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT text1, text2 FROM tblTable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$items = array();
// output data of each row
while($row = $result->fetch_assoc()) {
$item = array("Texte1" => $row['text1'],
"Texte2" => $row['text2']);
array_push($items, $item);
}
echo json_encode($items);
} else {
echo "0 results";
}
$conn->close();
?>
此代码调用PHP文件,获取响应并将其转换为项目列表。这是C#代码:
using System.Net.Http;
using Newtonsoft.Json;
//....
private Uri uri;
private HttpClient client;
private List<Items> item;
public async Task<List<Items>> ReadData()
{
client = new HttpClient();
uri = new Uri("http://adress/getdata.php");
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
item = JsonConvert.DeserializeObject<List<Items>>(content);
}
return item;
}
public class Items
{
public string text1 { get; set;}
public string text2 { get; set;}
}
所以现在,ReadData方法的返回类型是List<Items>
但是如何在List<string>
或简单的字符串中返回它们?
Linq的一些选项(不要忘记包括“使用System.Linq;”)。我更喜欢使用选项2
var mylist = item.Where(x => x != null)
.Select(x => new { x.text1, x.text2 }).ToList();
List<List<string>> mylist = listItems.Where(x => x != null)
.Select(x => new List<string>{ x.text1, x.text2}).ToList();