.Contains() on a List of Custom Class Objects

.Contains() on a list of custom class objects

You need to implement IEquatable or override Equals() and GetHashCode()

For example:

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

C# list of custom class .Contains()

ParamDT is also a list, you have to check its items also individually to compare properly.

this.ParamDT.Equals(item.ParamDT);

Having said that, list is not the structure you should be using if you want single instances of your object. There is a lot of overhead trying to search for equality in list as you will be searching the entire list. Try to use a set/dictionary based structure.

Your implementation of GetHasCode function is also not proper. It is based only on Name property while in equality you are using all the properties, this will lead to undesirable characteristics. Please read the MSDN documentation for a better implementation.

Checking if a variable exist in a List of custom class

Your code is not working because you are checking itemName and the item itself.

Do it as follows:

boolean found=false;
for(Grocery g: GroceryActivity.list){
if(g.getItemName().equals(itemName)){
found=true;
break;
}
}
if(!found){
//...do whatever you want to do
}

Where itemName is the name of the item you want to checkout and getItemName is the getter of itemName in class Grocery.

Using __contains__ on a list of custom class objects

This is a misuse of __contains__. You would expect to implement __contains__ on a class like UserList.

A better way to do this is to just access the id attribute directly in generator expression or list comprehension (rather than using the in operator). eg.

class User(object):
def __init__(self, id=None, name=None):
self.id = id
self.name = name

user = User(1, 'name_1')
assert 1 == user.id

user_list = [user, User(2, 'name_2')]
assert any(2 == u.id for u in user_list)

Then for your random example, you'd use a set or dictionary to store the ids of the users that already exist.

users = [User(x, 'name_{}'.format(x)) for x in xrange(5)]
ids = set(u.id for u in users)

for x in xrange(5):
i = randint(2,6)
if i in ids:
print("User id already exists: {}".format(i))
else:
print("{} is not in users list. Creating new user with id: {}".format(i, i))
ids.add(i)
users.append(User(i, 'new_user{}'.format(i)))

C# Check if List contains a custom object with the same value

If you only want to to check against the the ID field and ignore others then you can do :

if(!NemesisList.Any(n=> n.Dex_ID == nemesis.Dex_ID))

otherwise if you want to perform comparison for all the fields then you can override Equals and GetHashCode.

See: Correct way to override Equals() and GetHashCode()

Checking list for custom object

Assuming you have a code like this:

List<CustomObject> listOfCustomObjects = new List<CustomObject>();

Solution 1

If so, you can use listOfCustomObjects.Contains(customObject) to find out if customObject is in listOfCustomObjects. You should add using System.Linq; to the top of your code in order to use this method.

Solution 2

Another way to not have duplicates in your list is basically not using a List. You can use HashSet instead. With this method, duplicate objects won't be added to your list automatically. HashSet is also in LINQ Library, so you should add the line using System.Linq; for this solution too. Here's an example how to create a new HashSet with your CustomObject class:

HashSet<CustomObject> setOfCustomObjects = new HashSet<CustomObject>();

How to print a list containing custom objects from a class?

There are many ways you could do this. Here's one:

class Cat:
def __init__(self, name, colour):
self.name = name
self.colour = colour
def __repr__(self):
return f"'{self.name} {self.colour}'"

class ListOfCats:
def __init__(self):
self.loc = []
def addcat(self, cat):
self.loc.append(cat)
def __repr__(self):
return str(self.loc)

LOC = ListOfCats()

LOC.addcat(Cat('Lulu', 'red'))
LOC.addcat(Cat('Lala', 'white'))

print(LOC)

Output:

['Lulu red', 'Lala white']

Storing a custom object which contains a list in a database

turns out i had to use [ignore] like this:

[Table("Room")]
public class Room
{
[PrimaryKey, AutoIncrement]
public int id { get; set; }

public string RoomName { get; set; }

public string NFC_UId { get; set; }

[Ignore]
public List<Switch> RoomSwitches { get; set; } //note the get and set instead of new list

public Room()
{

}

public getswitches(){} <---
}

I am now using a function inside the room class(marked with <---) to get the switches after the room has been loaded from the database.

Sort a list of custom object with String contains in the object

You can use a custom key function using the name property of your objects:

boxList.sort(key = lambda box : box.name)

Alternatively, you can use operator.itemgetter instead of a lambda function:

from operator import itemgetter
boxList.sort(key = itemgetter('name'))

Checking if an array of custom objects contain a specific custom object

There are two contains functions:

extension SequenceType where Generator.Element : Equatable {
/// Return `true` iff `element` is in `self`.
@warn_unused_result
public func contains(element: Self.Generator.Element) -> Bool
}

extension SequenceType {
/// Return `true` iff an element in `self` satisfies `predicate`.
@warn_unused_result
public func contains(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool
}

The compiler is complaining because the compiler knows that Person is not Equatable and thus contains needs to have a predicate but alex is not a predicate.

If the people in your array are Equatable (they aren't) then you could use:

person.list.contains(alex)

Since they aren't equatable, you could use the second contains function with:

person.list.contains { $0.name == alex.name }

or, as Martin R points out, based on 'identity' with:

person.list.contains { $0 === alex }

or you could make Person be Equatable (based on either name or identity).



Related Topics



Leave a reply



Submit