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