C
C#8mo 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
Angius8mo ago
.Contains() for example
Ewan
EwanOP8mo ago
AH
Angius
Angius8mo ago
Or .Any() with a predicate
Ewan
EwanOP8mo ago
gotcha thank you!
Angius
Angius8mo ago
Or use a hashset, it deduplicates automatically
Ewan
EwanOP8mo ago
got it thanks!
Angius
Angius8mo 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
EwanOP8mo ago
if (!_customers.Contains(customer)) { _customers.Add(customer); } } i mean this works right?
Angius
Angius8mo ago
Well, reference types use reference comparison So it works if a reference to that particular customer exists on the _customers list
Ewan
EwanOP8mo ago
ah ok i havnt learnt hashsets so im good
MODiX
MODiX8mo 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
Angius8mo ago
As you can see Different references
Ewan
EwanOP8mo ago
oh i see oh right well they are named different
Angius
Angius8mo ago
Values inside of the class don't matter whatsoever, only the reference
Ewan
EwanOP8mo ago
right
Angius
Angius8mo ago
When it comes to .Contains() at least
Ewan
EwanOP8mo ago
ok gotcha
Angius
Angius8mo ago
.Any() with a predicate might be safer
MODiX
MODiX8mo 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
EwanOP8mo 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