C# Linq到Sql-筛选表结果
我有一个SQL表:C# Linq到Sql-筛选表结果,c#,linq,C#,Linq,我有一个SQL表: Id FirstName LastName DateTime 1 John Doe 2016-09-27 20:45:52.293 2 John Doe 2016-09-27 20:45:53.620 3 John Doe 2016-09-27 20:46:02.370 4 John Doe 2016-09-27 20:46:02
Id FirstName LastName DateTime
1 John Doe 2016-09-27 20:45:52.293
2 John Doe 2016-09-27 20:45:53.620
3 John Doe 2016-09-27 20:46:02.370
4 John Doe 2016-09-27 20:46:02.533
5 John Doe 2016-09-27 20:46:02.680
6 John Doe 2016-09-27 20:46:02.820
以及一个类和实例:
public class Cus
{
public int Id { get; set; }
public string First { get; set; }
public string Last { get; set; }
public DateTime DateTime { get; set; }
}
List<Cus> o = new List<Cus>()
{
new Cus()
{
Id = 1,
First = "John",
Last = "Doe"
},
new Cus()
{
Id = 2,
First = "John",
Last = "Doe"
},
new Cus()
{
Id = 3,
First = "John",
Last = "Doe"
}
};
但我想在我的表中只接受列表中的客户(使用Id
)
如何做到这一点?您可以从o
集合中获取所有Id,并使用Contains
方法筛选出我们创建的用户Id集合中的客户Id
//Get the Id's from o collection.
var userIds = o.Select(f=>f.Id);
//Get the customers who's id belongs to the above collection
var customers = yourDbContext.Customers.Where(x => userIds.Contains(x.Id)).ToList();
您可以从o
集合中获取所有Id,并使用Contains
方法筛选出Id位于我们创建的用户Id集合中的客户
//Get the Id's from o collection.
var userIds = o.Select(f=>f.Id);
//Get the customers who's id belongs to the above collection
var customers = yourDbContext.Customers.Where(x => userIds.Contains(x.Id)).ToList();
创建ID列表并使用Contains
可能是最有效的方法,因为它可以转换为SQL中的IN
子句:
List<int> ids = o.Select(c => c.Id).ToList();
using(DataClassesDataContext Context = new DataClassesDataContext())
{
var Customers = Context.Customers.Where(x => ids.Contains(x.Id));
}
List-Id=o.Select(c=>c.Id.ToList();
使用(DataClassesDataContext上下文=新DataClassesDataContext())
{
var Customers=Context.Customers.Where(x=>ids.Contains(x.Id));
}
创建ID列表并使用Contains
可能是最有效的方法,因为它可以转换为SQL中的子句中的:
List<int> ids = o.Select(c => c.Id).ToList();
using(DataClassesDataContext Context = new DataClassesDataContext())
{
var Customers = Context.Customers.Where(x => ids.Contains(x.Id));
}
List-Id=o.Select(c=>c.Id.ToList();
使用(DataClassesDataContext上下文=新DataClassesDataContext())
{
var Customers=Context.Customers.Where(x=>ids.Contains(x.Id));
}