tags:

views:

683

answers:

5

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.

+8  A: 

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");
Jon Skeet
It's indeed the easiest. Although I would really have liked the person.Contacts.Contains("aPerson"); Just because that would give me the opportunity to put the comparing code at a central place.
borisCallens
Putting the code in an extension method like I suggested in a different question would enable the person.Contacts.Contains("aPerson") syntax.
configurator
I'd write a slightly different extension method, personally, to allow person.Contacts.Contains(p => p.Name, "aPerson"). That makes it really obvious what's going on. It's on my list for "enhanced LINQ to objects"...
Jon Skeet
A: 

You could create the extension method

public static bool Contains(this IList<Person> list, string name) {
    return list.Any(c => c.Name == name);
}
configurator
+2  A: 

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"; });
Sekhat
+1  A: 

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;
Marc Gravell
A: 

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);
    }
}
Ricardo Villamil