简体   繁体   English

将列表传递给linq查询

[英]passing list to linq query

I have a linq query that returns a list and the result looks like this: 我有一个linq查询,它返回一个列表,结果看起来像这样:

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

This list is of type MyModel like this: 此列表的类型为MyModel,如下所示:

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 现在,我要做的就是将此列表传递给一个名为GetPatientInfo的函数,并返回另一个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. 我一直在写where子句和调用语句。 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. 但是,这是否真正有效取决于您所使用的LINQ提供程序。 Is this LINQ To SQL? 这是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. 如果真是这样,您可能被迫在MyDC.Table( MyDC.Table.AsEnumerable() )上抛出AsEnumerable() ),或者完全重新考虑您的查询。 AsEnumerable will bring the entire table into memory and then use LINQ to Objects from that point on, potentially an expensive move. 从那时起,AsEnumerable会将整个表带入内存,然后使用LINQ to Objects,这可能是昂贵的举动。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM