Contains <T> () and how to implement it

Say class

Person  
+Name: string  
+Contacts: List<Person>

I want to check if a person has contact with a specific name without creating an instance of a fictitious person.

person.Contacts.Contains<string>("aPersonName");

This should check all persons in the contact list if their Name.Equals ("aPersonName"); I see that there is already available, but I do not know where I should implement its logic.

+3
source share
5 answers

Perhaps the easiest way is to use Enumerable.Any :

 return person.Contacts.Any(person => person.Name=="aPersonName");

Alternatively, execute a project, and then:

 return person.Select(person => person.Name).Contains("aPersonName");
+12
source

I assume Contacts are contacts for this person (the person in your code snippet)

contains, T true false, . , , IList.Exists , .

example (# 3.0)

bool hasContact = person.Contacts.Exists(p => p.Name == "aPersonName");

(# 2.0)

bool hasContact = person.Contacts.Exists(delegate(Person p){ return p.Name == "aPersonName"; });
+2

Jon Any, # 2.0 # 3.0 .NET 2.0/3.0 LINQBridge, - List<T>.Find List<T>.Exists. Find, Exists , ; -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;
+1

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

, , - . , , :

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);
    }
}  
0

Source: https://habr.com/ru/post/1699515/


All Articles