views:

230

answers:

3

I'm new to using Linq and just started a side project to learn some of the basics. I'm currently using Linq to Sql and all my DB Table relationships worked very well. Currently I have a Client table and a Project table. Each Client can have 1 or more Projects. Therefore, as you'd expect each Client object has a collection of Project objects after Linq does its magic.

I'm using the below code and it works well, but I think there is a better way of doing it. I need to pass my method a ProjectID and then select that Project from the Client:

    private void PopulateStatusView(int projectID)
    {
        MyDataContext db = new MyDataContext();

        var client = (from u in db.Clients
                      where u.id == Convert.ToInt32(Session["ClientID"])
                      select u).SingleOrDefault();

        if (client != null)
        {
            foreach (Project currentProject in client.Projects)
            {
                if (currentProject.id == projectID)
                {
                    // Project Selected Here
                    statusProjectName.Text = currentProject.name;
                }
            }
        }
        else
        {
             // Session Expired
        }
    }

Can anyone let me know if there's a better solution rather than looping over each Project.

Thank you.

+2  A: 

To get the client which has the specific project ID:

var client = (from u in db.Clients
              where u.id == Convert.ToInt32(Session["ClientID"]) && 
                    u.Projects.Any(x=>x.id == projectID)
              select u).SingleOrDefault();

To get the project:

var project = (from u in db.Clients
              where u.id == Convert.ToInt32(Session["ClientID"]) && 
                    u.Projects.Any(x=>x.id == projectID)
              select u.Projects.Where(x=>x.id == projectID).Single()).SingleOrDefault();
Mehrdad Afshari
Thanks, this is the most concise. Is there a big difference between using Projects.Any vs Projects.Where in this case?
Sean
Any returns a *boolean* value to indicate whether or not such a project ID exists. Where returns those projects that satisfy that ID. "Any(x)" is semantically like "Where(x).Count() > 0"
Mehrdad Afshari
Great, Thanks again
Sean
+1  A: 

Try something like this:

clients.Projects.Where(
    p => p.id == projectID 
    && p.name == statusProjectName.Text);
Andrew Hare
Thank you, I should note that I'm setting the Text of statusProjectName to the project name but your approach still solves the problem.
Sean
+1  A: 

You can replace the foreach look up with something like:

var project = client.Projects.Where(p=>p.id==projectID).SingleOrDefault();
if (project != null) statusProjectName.Text = project.name;
Jonathan