UWP - 比较JSON和数据库的数据

Ros*_*ose 6 c# database json uwp

我有一个名为ebookstore.db的数据库,如下所示: 数据库

和JSON如下: JSON

我想当JSON上的slug与数据库中的标题不同时,它将显示带有JSON上的slug的数据量,这与ukomikText中数据库中的标题不同.

码:

    string judulbuku;
     try
     {
        string urlPath1 = "https://...";
        var httpClient1 = new HttpClient(new HttpClientHandler());
        httpClient1.DefaultRequestHeaders.TryAddWithoutValidation("KIAT-API-KEY", "....");
        var values1 = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("halaman", 1),
            new KeyValuePair<string, string>("limit", 100),
        };

         var response1 = await httpClient1.PostAsync(urlPath1, new FormUrlEncodedContent(values1));
         response1.EnsureSuccessStatusCode();

        if (!response1.IsSuccessStatusCode)
        {
            MessageDialog messageDialog = new MessageDialog("Memeriksa update Komik gagal", "Gangguan Server");
            await messageDialog.ShowAsync();
        }
        string jsonText1 = await response1.Content.ReadAsStringAsync();
        JsonObject jsonObject1 = JsonObject.Parse(jsonText1);
        JsonArray jsonData1 = jsonObject1["data"].GetArray();

        foreach (JsonValue groupValue in jsonData1)
        {
            JsonObject groupObject = groupValue.GetObject();

            string id = groupObject["id"].GetString();
            string judul = groupObject["judul"].GetString();
            string slug = groupObject["slug"].GetString();

            BukuUpdate file1 = new BukuUpdate();
            file1.ID = id;
            file1.Judul = judul;
            file1.Slug = slug;

            List<String> title = sqlhelp.GetKomikData();
            foreach (string juduldb in title)
            {
                judulbuku = juduldb.Substring(juduldb.IndexOf('.') + 1);
                if (judulbuku != file1.Slug.Replace("-", "_") + ".pdf")
                {
                    BukuData.Add(file1);
                    ListBuku.ItemsSource = BukuData;
                }
                else
                {
                    ukomikText.Text = "belum tersedia komik yang baru";
                    ukomikText.Visibility = Visibility.Visible;
                }
            }
        }
        if (ListBuku.Items.Count > 0)
        {
            ukomikText.Text = BukuData.Count + " komik baru";
            ukomikText.Visibility = Visibility.Visible;
            jumlahbuku = BukuData.Count;
        }
        else
        {
            ukomikText.Text = "belum tersedia komik yang baru";
            ukomikText.Visibility = Visibility.Visible;
        }

 public static List<String> GetKomikData()
        {
            List<String> entries = new List<string>();

            using (SqliteConnection db =
                new SqliteConnection("Filename=ebookstore.db"))
            {
                db.Open();
                SqliteCommand selectCommand = new SqliteCommand
                    ("SELECT title FROM books where folder_id = 67", db);
                SqliteDataReader query = selectCommand.ExecuteReader();
                while (query.Read())
                {
                    entries.Add(query.GetString(0));
                }
                db.Close();
            }
            return entries;
        }
Run Code Online (Sandbox Code Playgroud)

BukuUpdate.cs:

public string ID { get; set; }
public string Judul { get; set; }
public string Slug { get; set; }
Run Code Online (Sandbox Code Playgroud)

我有一个问题,就是当检查JSON上的slu ,,然后显示的slug是第一个slug在数据库中重复显示尽可能多的数据,之后在数据库上反复显示第二个slug,等等, 如下: 结果

如何解决它,以便不重复显示JSON上的slug(根据JSON上的数据量)?

Mar*_*und 1

问题是你有两个嵌套foreach循环。该代码在简化伪代码中的作用:

For each item in JSON
   Load all rows from DB
   And for each loaded row
      Check if the current JSON item matches the row from DB and if not, output
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,如果NJSON 中有项目并且M数据库中有行,那么这不可避免地会导致N*M输出行,除了那些罕见的 JSON 项目与数据库中的特定行匹配的输出行。

如果我理解正确的话,我假设您想检查是否有一行与 JSON 项匹配,如果没有,则输出它。您可以通过以下方式执行此操作:

List<String> title = sqlhelp.GetKomikData();
HashSet<string> dbItems = new HashSet<string>();
foreach (string juduldb in title)
{
    judulbuku = juduldb.Substring(juduldb.IndexOf('.') + 1);
    dbItems.Add( judulbuku );
}

...

foreach ( JsonValue groupValue in jsonData1 )
{
    ...

    //instead of the second foreach

    if ( !dbItems.Contains( file1.Slug.Replace("-", "_") + ".pdf" ) )
    {
         //item is not in database
    }
    else
    {
         //item is in database
    }
}
Run Code Online (Sandbox Code Playgroud)

附加提示

  • 避免GetKomikDataforeach. 此方法没有任何参数,这意味着您只是无缘无故地一次又一次地访问数据库,这需要时间并显着减慢执行速度。GetKomikData相反,在第一个之前仅调用一次foreach,然后仅使用title变量。
  • 不要ItemsSource在每次集合更改时都进行分配。这会不必要地减慢 UI 线程的速度,因为每次循环都必须重新加载所有项目。相反,仅在外部属性之后分配该属性一次foreach
  • 用一种语言编写代码。当您开始将英语和印度尼西亚语的变量名称混合时,代码会变得混乱且可读性较差,并会增加认知开销。
  • 避免使用非描述性变量名称,例如file1jsonObject1。变量名称应该清楚并告诉您它包含什么。当末尾有数字时,通常意味着可以更清楚地命名。
  • 使用复数作为列表变量名称 - 而不是title使用titles