这个怎么样?
今天我来问如何比较两个不同的JSON,假设第一个JSON有7个元素,但第二个JSON有9个元素。
如何让我的程序确定哪两个元素是新元素?
这是我尝试过的代码,但效果不太好。
bool check = false;
foreach (var item in jsonTwo["contentItems"])
{
foreach (var item2 in jsonOne["contentItems"])
{
if (item["contentFields"]["title"].ToString() == item2["contentFields"]["title"].ToString())
{
check = true;
}
else
{ check = false; }
}
if (check == false)
{
Console.WriteLine(item["contentFields"]["title"].ToString());
}
}
感谢所有的帮助!!
public class User
{
public string Name { get; set; }
public string City { get; set; }
public int Age { get; set; }
public override string ToString()
{
return $"{Name}-{City}-{Age}";
}
}
public class UserEqualityComparer : IEqualityComparer<User>
{
public bool Equals(User x, User y)
{
return x.Age == y.Age && x.City == y.City;
}
public int GetHashCode(User obj)
{
return 0;
}
}
static void Main(string[] args)
{
var jsonArray = new List<string>()
{
@"{name: ""John"", age: 31, city: ""New York""}",
@"{name: ""John2"", age: 31, city: ""New York""}",
@"{name: ""John3"", age: 33, city: ""New York""}",
};
var users = jsonArray.Select(m => JsonConvert.DeserializeObject<User>(m)).ToList();
var groups = users.GroupBy(m => m, new UserEqualityComparer()).ToList();
foreach (var group in groups)
{
foreach (var item in group)
{
Console.WriteLine(item.ToString());
}
Console.WriteLine("------------");
}
Console.ReadLine();
}