program tip

.Contains () 사용자 정의 클래스 객체 목록

radiobox 2020. 9. 23. 07:29
반응형

.Contains () 사용자 정의 클래스 객체 목록


.Contains()사용자 지정 개체 목록 에서 함수 를 사용하려고 합니다.

다음은 목록입니다.

List<CartProduct> CartProducts = new List<CartProduct>();

그리고 CartProduct:

public class CartProduct
{
    public Int32 ID;
    public String Name;
    public Int32 Number;
    public Decimal CurrentPrice;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="ID">The ID of the product</param>
    /// <param name="Name">The name of the product</param>
    /// <param name="Number">The total number of that product</param>
    /// <param name="CurrentPrice">The currentprice for the product (1 piece)</param>
    public CartProduct(Int32 ID, String Name, Int32 Number, Decimal CurrentPrice)
    {
        this.ID = ID;
        this.Name = Name;
        this.Number = Number;
        this.CurrentPrice = CurrentPrice;
    }
    public String ToString()
    {
        return Name;
    }
}

그래서 나는 목록에서 비슷한 카트 제품을 찾으려고 노력합니다.

if (CartProducts.Contains(p))

그러나 유사한 카트 제품을 무시하고 ID가 무엇인지 확인하지 못하는 것 같습니다. 아니면 전부?

미리 감사드립니다! :)


구현 IEquatable하거나 재정의 해야 Equals()하며GetHashCode()

예를 들면 :

public class CartProduct : IEquatable<CartProduct>
{
    public Int32 ID;
    public String Name;
    public Int32 Number;
    public Decimal CurrentPrice;

    public CartProduct(Int32 ID, String Name, Int32 Number, Decimal CurrentPrice)
    {
        this.ID = ID;
        this.Name = Name;
        this.Number = Number;
        this.CurrentPrice = CurrentPrice;
    }

    public String ToString()
    {
        return Name;
    }

    public bool Equals( CartProduct other )
    {
        // Would still want to check for null etc. first.
        return this.ID == other.ID && 
               this.Name == other.Name && 
               this.Number == other.Number && 
               this.CurrentPrice == other.CurrentPrice;
    }
}

.NET 3.5 이상을 사용하는 경우 LINQ 확장 메서드를 사용하여 확장 메서드로 "포함"검사를 수행 할 수 있습니다 Any.

if(CartProducts.Any(prod => prod.ID == p.ID))

CartProductsID와 일치하는 ID가 있는 제품이 있는지 확인합니다 p. =>검사를 수행하기 위해 뒤에 부울 표현식을 넣을 수 있습니다 .

This also has the benefit of working for LINQ-to-SQL queries as well as in-memory queries, where Contains doesn't.


It checks to see whether the specific object is contained in the list.

You might be better using the Find method on the list.

Here's an example

List<CartProduct> lst = new List<CartProduct>();

CartProduct objBeer;
objBeer = lst.Find(x => (x.Name == "Beer"));

Hope that helps

You should also look at LinQ - overkill for this perhaps, but a useful tool nonetheless...


By default reference types have reference equality (i.e. two instances are only equal if they are the same object).

You need to override Object.Equals (and Object.GetHashCode to match) to implement your own equality. (And it is then good practice to implement an equality, ==, operator.)


If you want to have control over this you need to implement the [IEquatable interface][1]

[1]: http://This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable.Equals method for T (the type of values in the list).


Implement override Equals() and GetHashCode()

public class CartProduct
{
    public Int32 ID;
    ...

    public CartProduct(Int32 ID, ...)
    {
        this.ID = ID;
        ...
    }

    public override int GetHashCode()
    {
        return ID;
    }

    public override bool Equals(Object obj)
        {
            if (obj == null || !(obj is CartProduct))
                return false;
            else
                return GetHashCode() == ((CartProduct)obj).GetHashCode();
        }

}

used:

if (CartProducts.Contains(p))

참고URL : https://stackoverflow.com/questions/2629124/contains-on-a-list-of-custom-class-objects

반응형