Linq to Sql - 过滤表结果

时间:2016-09-27 19:35:12

标签: 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.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}})

的客户。

怎么做?

2 个答案:

答案 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));
}