我希望简化包含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
}
}
}谢谢。
发布于 2013-04-26 00:21:24
您可以使用搜索效率更高的集合,例如HashSet,而不是对parseUsers中的每一项对emails集合进行线性搜索
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-26 00:48:26
不会提高性能,但可以提高可读性:
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);
}
}https://stackoverflow.com/questions/16219818
复制相似问题