[英]Compare two objects List<Items> in C# UWP
我正在尝试根据服务器的更新时间(基于数据库的保存)下载基于服务器的文件(PDF)。 在下载之前,我想将它们与本地计算机上的现有文件列表进行比较。 问题是比较对象字段给出错误的输出。
这两个文件都是基于json的文件,在下面的“ ITEMS”对象中进行了解析。 我正在使用Visual Studio 2015和C#。 后端是Laravel REST。
class Items
{
public int id { get; set; }
public string branch { get; set; }
public string item { get; set; }
public string link { get; set; }
public int active { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
}
这就是我解析服务器和本地列表(都是JSON)的方式:
for (int i = 0; i < obj.Count; i++)
{
JObject row = JObject.Parse(obj[i].ToString());
Items newItem = new Items();
newItem.id = int.Parse(row["id"].ToString());
newItem.branch = row["branch"].ToString();
newItem.item = row["item"].ToString();
newItem.link = row["link"].ToString();
newItem.created_at = row["created_at"].ToString();
newItem.updated_at = row["updated_at"].ToString();
files.Add(newItem);
}
我正在使用foreach循环来检查Updated_at字段是否相等
// Compare files
foreach (Items item in files)
{
foreach(Items it in filesToDownload)
{
if (!it.updated_at.Equals(item.updated_at))
{
//Download the file
//Create a new list of files to download
}
}
}
for (int i = 0; i < obj.Count; i++)
{
JObject row = JObject.Parse(obj[i].ToString());
Items newItem = new Items();
newItem.id = int.Parse(row["id"].ToString());
newItem.item = row["branch"].ToString();
newItem.link = row["item"].ToString();
newItem.item = row["link"].ToString();
newItem.item = row["created_at"].ToString();
newItem.item = row["updated_at"].ToString();
files.Add(newItem);
}
您正在为所有变量设置item
属性。
尝试:
for (int i = 0; i < obj.Count; i++)
{
JObject row = JObject.Parse(obj[i].ToString());
Items newItem = new Items();
newItem.id = int.Parse(row["id"].ToString());
newItem.branch = row["branch"].ToString();
newItem.item = row["item"].ToString();
newItem.link = row["link"].ToString();
newItem.created_at = row["created_at"].ToString();
newItem.updated_at = row["updated_at"].ToString();
files.Add(newItem);
}
如果列表确实是可比较的,并且它们具有完全相同的格式,例如,item.updated_at C#可以使用“函数相交”或“除”来“本地”比较列表;
请记住,该程序不会检查真实性,因此如果您认为通过遍历数组已经正确并仍然得到错误的结果,那么我将从检查数据开始,如果这可能是问题所在。
因为看起来foreach循环会像Intersect和Except一样做。
首先调试循环,然后使用Expression-Checker(或诸如OzCode这样的简单程序)自己比较列表。
另外,我还是比较ID而不是使用时间戳的粉丝。 如果它们兼容。
两个有用的链接:
我认为您只是复制+粘贴过多... =)
for (int i = 0; i < obj.Count; i++)
{
JObject row = JObject.Parse(obj[i].ToString());
Items newItem = new Items();
newItem.id = int.Parse(row["id"].ToString());
newItem.item = row["branch"].ToString();
newItem.link = row["item"].ToString();
newItem.item = row["link"].ToString();
newItem.item = row["created_at"].ToString();
newItem.item = row["updated_at"].ToString();
files.Add(newItem);
}
您重复了newItem.item
几次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.