Reputation: 93317
Say a class
Person
+Name: string
+Contacts: List<Person>
I want to be able to check if a person has a contact with a certain name without having to create a dummy Person instance.
person.Contacts.Contains<string>("aPersonName");
This should check all persons in the Contacts list if their Name.Equals("aPersonName"); I see that there is a Contains already available, but I don't know where I should implement it's logic.
Upvotes: 4
Views: 7755
Reputation: 41620
You could create the extension method
public static bool Contains(this IList<Person> list, string name) {
return list.Any(c => c.Name == name);
}
Upvotes: 0
Reputation: 5107
The solutions already presented by Jon Skeet and yapiskan are the way to go. If you need exactly what you're stating then you could write an extension method:
public static class ContactListExtensions
{
public static bool Contains<T>(this List<Person> contacts, string aPersonName)
{
//Then use any of the already suggested solutions like:
return contacts.Contains(c => c.Name == aPersonName);
}
}
Upvotes: 0
Reputation: 1062630
I'd agree with Jon's Any
, but if you are stuck with C# 2.0, or C# 3.0 with .NET 2.0/3.0 and no LINQBridge, then another approach is List<T>.Find
or List<T>.Exists
. I'll illustrate with Find
, since Exists
got posted just as I was about to hit the button ;-p
// C# 2.0
bool knowsFred = person.Contacts.Find(delegate(Person x) { return x.Name == "Fred"; }) != null;
// C# 3.0
bool knowsFred = person.Contacts.Find(x => x.Name == "Fred") != null;
Upvotes: 1
Reputation: 4479
I'm assuming the Contacts is the Contacts for the person in question (person in your code snippit)
List has a contains method that takes an object of type T as a parameter and returns true or false if that object exists in the list. What your wanting is IList.Exists method, Which takes a predicate.
example (c# 3.0)
bool hasContact = person.Contacts.Exists(p => p.Name == "aPersonName");
or (c# 2.0)
bool hasContact = person.Contacts.Exists(delegate(Person p){ return p.Name == "aPersonName"; });
Upvotes: 2
Reputation: 1500135
It's probably easiest to use Enumerable.Any:
return person.Contacts.Any(person => person.Name=="aPersonName");
Alternatively, project and then contain:
return person.Select(person => person.Name).Contains("aPersonName");
Upvotes: 13