Reputation: 2607
I have a AccountContacts class that contains a data member contacts which is a list of type ContactInfo.
Each ContactInfo class has two members. 1. List that holds ContactTypes (strings) 2. A Contact Object.
so, it looks like
Class AccountContacts
{
List<ContactInfo> Contacts;
}
Class ContactInfo
{
List<string> ContactType;
Contact UserContact;
}
now If I have an AccountContacts object (ac), how can I get a Contact object where the ContactType list in ContactInfo contains a specific string.
And by the way, each ContactType list is distinct to other. So at a time on Contact object can be returned.
I tried some thing like this.
Contact myContact = ac.Contacts.Find(c => c.ContactType.Contains("specificString")).UserContact;
I am able to get myContact. just want to know is there any better way of doing this?
Upvotes: 2
Views: 9505
Reputation: 2504
ac.Contacts
.Where(x => x.ContactType.Contains("string"))
.Select(x => x.UserContact)
This will return list of Contacts that have "string" as ContactType.
Upvotes: 1
Reputation: 21501
You are using the Find
method which will produce a null
result if there is no match to your condition, i.e. there is no ContactType
matching your input.
This will cause a NullReferenceException
when you call .UserContact
because you can't do null.UserContact
.
null
:var contact = (ac.Contacts.Where(c => c.ContactType.Contains("specificString")).Select(c => c.UserContact)).FirstOrDefault();
This uses the Contains
method to determine if the list has the string you are looking for.
If a match is found then the Contact
will be selected
Then the FirstOrDefault
will take the first record or return null
.
Upvotes: 4
Reputation: 1102
If they're guaranteed to be distinct:
var contact = ac.Contacts.SingleOrDefault(c => c.ContractType.Contains("string"));
if (contact != null)
{
var userContact = contact.UserContact;
}
else
{
// handle not found situation
}
Upvotes: 1