I have a linq query that returns开发者_如何学C 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. Thank you for suggestions.
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();
}
}
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.
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;
}
}
精彩评论