使用LINQ返回与值列表匹配的行列表

时间:2018-07-08 04:38:59

标签: c# linq

我有一个查询,该查询接收一个包含所有ID的项目列表,而我需要在另一个表中进行搜索。例如,这是我的第一个表类:

public class Presave
    {
        public int PresaveID { get; set; }
        public int ArtistID { get; set; }
        public string AlbumName { get; set; }
        public DateTime? ReleaseDate { get; set; }

        public virtual ICollection<UserPresave> UserPresaves { get; set; }
    }

然后是我需要搜索的其他课程:

public class UserPresave
{
    [Key]
    public int UserID { get; set; }
    public int PresaveID { get; set; }
    public string AccessToken { get; set; }

    public virtual Presave Presave { get; set; }
}

这两者之间存在一对一(预保存)对多(用户预保存)的关系。

我想搜索包含与我通过的UserPresave类相同的PresaveID的所有Presave。但是请注意,列表中的每个PresaveID元素的Presave都不相同。我以为这个查询会工作:

public static List<UserPresave> GetAllUserPresavesByPresaveIDs(List<Presave> ids)
{
    using (var Context = GetContext())
    {
        return Context.UserPresaves.Where(x => x.PresaveID == ids.Contains(x.PresaveID)).ToList();
    }
}

但是在x.Presave下收到一个错误,指出我无法从int转换为presave。我哪里做错了?谢谢!

我从这个问题中得到了这个查询概念! https://stackoverflow.com/a/36164453/6480913

2 个答案:

答案 0 :(得分:1)

如下所示更改功能:

 public static List<UserPresave> GetAllUserPresavesByPresaveIDs(List<Presave> ids)
 {
     var hs = new HashSet<int>(ids.Select(x=>x.PresaveID));
     using (var Context = GetContext())
     {
         return Context.UserPresaves.Where(x => hs.Contains(x.PresaveID)).ToList();
     }
 }

您的问题是您使用的类型不一致。在此处使用HashSet可以大大提高大型数据集的性能。

答案 1 :(得分:0)

尝试此操作...您可以从Presaves表中检索数据,然后从UserPresaves表中获取关联数据

<body>
  <div class="some-class">
    <div id="popup">...</div>
  </div>
</body>
相关问题