JSON列出不使用Distinct命令

时间:2018-04-24 21:11:33

标签: asp.net json asp.net-mvc linq

目前我正在查询返回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视图时使用命令Distinct。

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

但由于某种原因,它仍然会重复。 我在这里做错了什么想法? 在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我最后使用Shyju的评论纠正了它。 我将Distinct更改为以下内容。

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;
        }
    }