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

C# 使用LINQ返回与值列表匹配的行列表,c#,linq,C#,Linq,我有一个查询,它接收一个项目列表,所有这些项目都包含我需要在不同表中搜索的不同ID。例如,下面是我的第一个table类: public class Presave { public int PresaveID { get; set; } public int ArtistID { get; set; } public string AlbumName { get; set; } public DateTime? Releas

我有一个查询,它接收一个项目列表,所有这些项目都包含我需要在不同表中搜索的不同ID。例如,下面是我的第一个table类:

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; }
    }
这两者之间存在一对多(userpresave)关系

我想搜索所有
UserPresave
,它们包含与
Presave
一级通行证相同的
PresaveID
。但请注意,对于列表中的每个
Presave
元素,此
PresaveID
并不相同。我认为这个查询会起作用:

public static List<UserPresave> GetAllUserPresavesByPresaveIDs(List<Presave> ids)
{
    using (var Context = GetContext())
    {
        return Context.UserPresaves.Where(x => x.PresaveID == ids.Contains(x.PresaveID)).ToList();
    }
}
public静态列表getAllUserPresavesByPresavids(列表ID)
{
使用(var Context=GetContext())
{
返回Context.UserPresaves.Where(x=>x.PresaveID==ids.Contains(x.PresaveID)).ToList();
}
}
但是我在
x.Presave
下得到一个错误,说明我无法从
int
转换到
Presave
。我哪里出错了?谢谢


我从这个问题中得到了这个查询概念

如图所示更改您的功能:

 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();
     }
 }
public静态列表getAllUserPresavesByPresavids(列表ID)
{
var hs=newhashset(id.Select(x=>x.PresaveID));
使用(var Context=GetContext())
{
返回Context.UserPresaves.Where(x=>hs.Contains(x.PresaveID)).ToList();
}
}

你的问题是你使用的类型不一致。在此处使用哈希集将大大提高大型数据集的性能。

试试这个……您可以从Presaves表中检索数据,然后从UserPresaves表中获取相关数据

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();
            }
        }
public静态列表getAllUserPresavesByPresavids(列表ID)
{
使用(var Context=GetContext())
{
返回Context.Presaves.Where(p=>p.UserPresaves.Any(a=>ids.Contains(a.Presave)).ToList();
}
}

真管用!还要感谢您提供的额外信息,我需要阅读更多关于lambda表达式和哈希集的信息。:)
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();
            }
        }