0

我希望简化以下包含 foreach 循环的代码,以最小化迭代和/或提高性能,因为每次迭代都会创建 LINQ 和集合:

foreach (Contact contact in Contacts) // phone contacts, around 500-1000
{
    IEnumerable<ContactEmailAddress> emails = contact.EmailAddresses; // each has multiple emails

    foreach (Friend parseUser in parseUsers) // could be many thousands
    {
        if (emails.Where(e => e.EmailAddress == parseUser.Email).ToList().Count > 0)
        {                        
            parseUser.AddContact(contact); // function call

            verifiedUsers.Add(parseUser); // add to my new aggregated list
        }
    }
}

谢谢。

4

2 回答 2

3

您可以使用可以更有效地搜索的集合,而不是对emails集合中的每个项目进行线性搜索,例如:parseUsersHashSet

foreach (Contact contact in Contacts) // phone contacts, around 500-1000
{
    HashSet<string> emails = new HashSet<string>(
        contact.EmailAddresses.Select(e => e.EmailAddress));

    foreach (Friend parseUser in parseUsers) // could be many thousands
    {
        if(emails.Contains(parseUser.Email))
        {
            parseUser.AddContact(contact); // function call

            verifiedUsers.Add(parseUser); // add to my new aggregated list
        }
    }
}
于 2013-04-25T16:21:23.870 回答
1

没有提高很多性能,但提高了可读性:

foreach (Friend parseUser in parseUsers) // could be many thousands
{
    var filterContacts = Contacts.Where(contact =>
                              contact.EmailAddresses.Contains(parseUser.Email));
    if (filterContact.Any())
    {
        parseUser.AddContacts(filterContacts);
        verifiedUsers.Add(parseUser);
    }
}
于 2013-04-25T16:48:25.803 回答