加速Linq查询

时间:2011-01-18 22:11:28

标签: c# linq join

我的课程结构如下

public class Email 
{
    public string Subject {get;set;}
    public string Message {get;set;}
    public Contact Sender {get;set;}
    public string SenderEmail {get;set;}
}
public class Contact
{
    public string Email {get;set;}
    public string Name {get;set;}
}

我分两部分运行我的Linq查询 首先,我选择所有电子邮件。

var query = from msg in context.Email
            select msg;

然后我将联系人详细信息分配给电子邮件类

List<Email> outputList = new List<Email>();
foreach (var item in query.ToList())
{
    var q = from contact in context.Contact
            where contact.Email = item.SenderEmail
            select contact;
    item.Sender = q.SingleOrDefault();
    outputList.Add(item);
}


return outputList;

无论如何,我可以运行连接查询,只需输出List而无需运行多个查询

2 个答案:

答案 0 :(得分:2)

我怀疑这应该有效:

var query = from msg in context.Email
            join contact in context.Contact 
                 on msg.SenderEmail equals contact.Email
                 into contacts
            select new { msg, contacts };

var list = query.ToList();
foreach (var pair in list)
{
    pair.msg.Sender = pair.contacts.FirstOrDefault();
}

var messages = list.Select(pair => pair.msg);

这使用群组联接。您还没有说过您正在使用哪个LINQ提供商,但我希望它适用于大多数提供商......

答案 1 :(得分:2)

我认为这样可以解决问题(警告:未经测试的代码):

    var qry = from email in context.Email
              join contact in context.Contact 
              on email.SenderEmail equals contact.Email
              into contacts
              select new { eml = email, sender = contacts.FirstOrDefault() };

    var items = qry.ToList();

    foreach (var item in items)
    {
        item.eml.Sender = item.sender;
        outputList.Add(item.eml);
    }

    return outputList;