C
C#7mo ago
Ewan

✅ Check if an item is in a list

For this if statement, how do i make it so if the parameter customer is not in the list, then it adds it to the list
No description
20 Replies
Angius
Angius7mo ago
.Contains() for example
Ewan
EwanOP7mo ago
AH
Angius
Angius7mo ago
Or .Any() with a predicate
Ewan
EwanOP7mo ago
gotcha thank you!
Angius
Angius7mo ago
Or use a hashset, it deduplicates automatically
Ewan
EwanOP7mo ago
got it thanks!
Angius
Angius7mo ago
Not sure how well it works with reference types, though. Might need either some overrides on the type or a custom comparer for the hashset
Ewan
EwanOP7mo ago
if (!_customers.Contains(customer)) { _customers.Add(customer); } } i mean this works right?
Angius
Angius7mo ago
Well, reference types use reference comparison So it works if a reference to that particular customer exists on the _customers list
Ewan
EwanOP7mo ago
ah ok i havnt learnt hashsets so im good
MODiX
MODiX7mo ago
Angius
REPL Result: Success
class Foo(string name)
{
public string Name { get; set; } = name;
}

List<Foo> foos = [ new Foo("Bob") ];
var bob = new Foo("Bob");

foos.Contains(bob)
class Foo(string name)
{
public string Name { get; set; } = name;
}

List<Foo> foos = [ new Foo("Bob") ];
var bob = new Foo("Bob");

foos.Contains(bob)
Result: bool
False
False
Compile: 426.010ms | Execution: 42.391ms | React with ❌ to remove this embed.
Angius
Angius7mo ago
As you can see Different references
Ewan
EwanOP7mo ago
oh i see oh right well they are named different
Angius
Angius7mo ago
Values inside of the class don't matter whatsoever, only the reference
Ewan
EwanOP7mo ago
right
Angius
Angius7mo ago
When it comes to .Contains() at least
Ewan
EwanOP7mo ago
ok gotcha
Angius
Angius7mo ago
.Any() with a predicate might be safer
MODiX
MODiX7mo ago
Angius
REPL Result: Success
class Foo(string name)
{
public string Name { get; set; } = name;
}

List<Foo> foos = [ new Foo("Bob") ];
var bob = new Foo("Bob");

foos.Any(f => f.Name == bob.Name)
class Foo(string name)
{
public string Name { get; set; } = name;
}

List<Foo> foos = [ new Foo("Bob") ];
var bob = new Foo("Bob");

foos.Any(f => f.Name == bob.Name)
Result: bool
True
True
Compile: 425.404ms | Execution: 102.865ms | React with ❌ to remove this embed.
Ewan
EwanOP7mo ago
its just a little program, it works so its fine haha oooo i see thanks!
Want results from more Discord servers?
Add your server