I have the code as below, how can I avoid using foreach below, I am looping through a list and adding key value into a Dictionary, is there anyway I can avoid the foreach loop in the below code and add values to the Dictionary
DataQueryResult<Agreement> _agreements = new DataQueryResult<Agreement>();
Dictionary<Guid, Contact> _contacts = new Dictionary<Guid, Contact>();
_agreements = this.agreementRepository.GetAgreementsByQuery(_parameters);
Agreement _agreement = _agreements?.Data?.FirstOrDefault();
if (_agreement.AgreementActive)
{
// add contactids for the agreemenet
var _agreementContacts = await this.contactRepository.GetAgreementContactsAsync(_agreement.AgreementId.Value, null);
foreach (var _contact in _agreementContacts.Data)
{
if (_contact.Role.RoleId == DCCommonConstants.RoleId.KeyPersonnel &&
_contact.PersonActive &&
!_contacts.ContainsKey(_contact.ContactId.Value))
{
_contacts.Add(_contact.ContactId.Value, _contact);
}
}
}
Any help would be appreciated greatly, thanks in advance.
You don't write why you want to do this, but something like the following should do the trick:
var contacts = _agreementContacts.Data
.Where(c => c.Role.RoleId == DCCommonConstants.RoleId.KeyPersonnel &&
c.PersonActive)
.GroupBy(c => c.ContactId.Value)
.ToDictionary(c => c.First().ContactId.Value, _contact => _contact);
As I read the GroupBy documentation, the elements in the group preserve the original ordering, so taking the First()
of those should be equivalent to checking whether the key is already in the dictionary.