我有一个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.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"
}
};
我使用Linq To Sql类来获取我的sql表中的所有记录。我这样做:
using(DataClassesDataContext Context = new DataClassesDataContext())
{
var Customers = Context.Customers.Where(x => x.Any(y => o. ????????;
}
但我想仅在List<Cus>
中使用Id
(使用{{1}})
怎么做?
答案 0 :(得分:6)
您可以从o
集合中获取所有ID,并使用Contains
方法过滤掉我们创建的用户ID集合中的客户ID。< / p>
//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();
答案 1 :(得分:2)
创建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));
}