List<T>清除重复某一项

最近项目中需要对购物车中重复的商品号进行排除,

本文的例子借鉴加上自己的整理,用的双重循环来操作

以下是代码

public class Cart
    {
        public int ID { get; set; }

        public decimal price { get; set; }
    }
 //进行简单的声明并实例化
        List<Cart> lstCart = new List<Cart>() 
        { 
            new Cart(){ID=1,price=100},
            new Cart(){ID=1,price=100},
            new Cart(){ID=3,price=200},
            new Cart(){ID=5,price=300}
            
        };

        //双重循环进行判断重复操作
        
        for (int i = 0; i < lstCart.Count; i++)
        {
            for (int j = lstCart.Count - 1; j > i; j--)
            {
                if (lstCart[i].ID == lstCart[j].ID)
                {
                    lstCart.Remove(lstCart[i]);
                }

            }
         
        }

        //输出结果
        foreach (var item in lstCart)
        {
            Response.Write("ID:" + item.ID + "Price:" + item.price + "<br/>");
        }
输出结果为:
ID:1Price:100
ID:3Price:200
ID:5Price:300
原文地址:https://www.cnblogs.com/youmeng/p/2837615.html