代码之家  ›  专栏  ›  技术社区  ›  Jordan Lewallen

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

  •  0
  • Jordan Lewallen  · 技术社区  · 6 年前

    我有一个查询,它接收所有包含不同ID的项目列表,我需要在不同的表中搜索这些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 一级通过。但是请注意这个 预先保存的 每个都不一样 预先保存 列表中的元素。我认为这个问题可以解决:

    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 回复  |  直到 6 年前
        1
  •  1
  •   MineR    6 年前

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

        2
  •  0
  •   Noor All Safaet    6 年前

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