JSON列出没有使用独特的命令删除重复项



当前我正在查询返回JSON字符串的Web服务。

url = @"redacted url;
returnValue = new WebClient().DownloadString(url);

我将返回结果放入模型类中定义的项目列表中。然后,我正在运行第二个JSON调用,搜索具有相同搜索词的其他字段。

url2 = @"redacted url2;
returnValue2 = new WebClient().DownloadString(url2);

我然后创建我的列表,然后使用addrange组合列表。

List<Order> shipments = JsonConvert.DeserializeObject<List<Order>>(returnValue);
List<Order> shipments2 = JsonConvert.DeserializeObject<List<Order>>(returnValue2);
shipments.AddRange(shipments2);

结果有一些重复。为了尝试并仅返回唯一记录,我在从控制器发送到我的MVC视图时使用了命令。

return View(shipments.OrderBy(x => x.dtDateReceived).Distinct().ToList());

,但由于某种原因,它仍在返回重复。关于我在这里做错什么的想法吗?预先感谢您的任何帮助!

我最终使用Shyju的评论对其进行了更正。我更改了以下内容。

return View(shipments.OrderBy(x => x.dtDateReceived).Distinct(new OrderComparer()).ToList());

然后构建以下比较函数

// Custom comparer for the Order class
    class OrderComparer : IEqualityComparer<Order>
    {
        // Orders are equal if their names and order numbers are equal.
        public bool Equals(Order x, Order y)
        {
            //Check whether the compared objects reference the same data.
            if (Object.ReferenceEquals(x, y)) return true;
            //Check whether any of the compared objects is null.
            if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                return false;
            //Check whether the order's properties are equal.
            return x.sWorkOrderNumber == y.sWorkOrderNumber && x.sCustomerOrderName == y.sCustomerOrderName;
        }
        // If Equals() returns true for a pair of objects 
        // then GetHashCode() must return the same value for these objects.
        public int GetHashCode(Order order)
        {
            //Check whether the object is null
            if (Object.ReferenceEquals(order, null)) return 0;
            //Get hash code for the sCustomerOrderName field if it is not null.
            int hashOrderName = order.sCustomerOrderName == null ? 0 : order.sCustomerOrderName.GetHashCode();
            //Get hash code for the sWorkOrderNumber field.
            int hashOrderCode = order.sWorkOrderNumber.GetHashCode();
            //Calculate the hash code for the order.
            return hashOrderName ^ hashOrderCode;
        }
    }

最新更新