Damon
Damon

Reputation: 75

Speed up Linq Query

I have my class structure as follows

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;}
}

and I run my Linq query in two parts First i select all the emails.

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

Then i assign the Contact details to the Email Class

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;

Is there anyway i can run a join query and simply output the List without having to run multiple queries

Upvotes: 1

Views: 1161

Answers (2)

Justin Morgan
Justin Morgan

Reputation: 30700

I think this would do the trick (warning: untested code):

    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;

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503799

I suspect this should work:

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);

This uses a group join. You haven't said which LINQ provider you're using, but I expect it should work for most providers...

Upvotes: 2

Related Questions