satya
satya

Reputation: 2607

Linq query to get an object from list of lists

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

Answers (3)

nZeus
nZeus

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

Scott
Scott

Reputation: 21501

Your Code:

  • 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.


Safer - Check for 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

Parker
Parker

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

Related Questions