frenchie
frenchie

Reputation: 52037

Passing list to Linq query

I have a Linq query that returns a list and the result looks like this:

protected void Page_Load(object sender, EventArgs e)
{
  var MyList = GetPatientsFromDB(TheUserID);
}

This list is of type MyModel like this:

MyModel
{
public int PatientID {get;set;}
}

Now what I'm looking to do is pass this list to a function called GetPatientInfo and return another list of MyOtherModel

MyOtherModel{
public int PatientID {get;set;}
public string Name {get;set;}
public string Region {get;set;}
}

I'm have some problems writing the second function.

I started with

public static List<MyOtherModel> GetPatientInfo(List<MyModel>
{

using (..... MyDC = new... DataContext)

{
     var OutputList = from f in MyDC.Table
                       where......?

}

I'm stuck on writing the where clause and the calling statement. How can I do that?

Upvotes: 2

Views: 6487

Answers (3)

Matt Greer
Matt Greer

Reputation: 62057

To keep it fully in query syntax, it would be something like this:

var OutputList = from f in MyDC.Table
    from m in list
    where f.PatientId == m.PatientId
    select f;

However, whether this actually works or not depends on what LINQ provider you are using. Is this LINQ To SQL? Objects? Entities? Depending on which provider this is, it may not have an implementation behind the scenes that can support this query. If that is the case, you may be forced to either throw in AsEnumerable() on MyDC.Table (MyDC.Table.AsEnumerable()), or rethink your query altogether. AsEnumerable will bring the entire table into memory and then use LINQ to Objects from that point on, potentially an expensive move.

Upvotes: 2

Joel C
Joel C

Reputation: 5567

public static List<MyOtherModel> GetPatientInfo(List<MyModel> patients)
{

    using (..... MyDC = new... DataContext)
    {
        var OutputList = from f in MyDC.Table
                         where patients.Any(p => p.PatientID == f.PatientID)
                         select f;
    }
}

Upvotes: 1

hunter
hunter

Reputation: 63552

public static List<MyOtherModel> GetPatientInfo(List<MyModel list>
{
    using (..... MyDC = new... DataContext)
    {
        var result = from f in MyDC.Table
                     where list.Select(m => m.PatientID).Contains(f.PatientID)
                     select f;

        return result.ToList();
    }
}

Upvotes: 4

Related Questions