2010-05-26 76 views
3

我想要获取表中单个列的值数组,例如,我有一个名为Customer(ID,Name)的表,并且想要获取所有客户的ID。我在LINQ查询:使用LINQ查询单列

var ids = db.Customers.Select(c=>c.ID).ToList(); 

该查询的答案是正确的,但我跑SQL Server Profiler中,只见这是本查询:

SELECT [t0].[ID], [t0].[Name] FROM [dbo].[Customer] AS [t0] 

我明白了LINQ选择所有列,然后创建ID字段的整数数组。

我如何写一个LINQ查询生成的SQL Server的查询:

SELECT [t0].[ID] FROM [dbo].[Customer] AS [t0] 

谢谢。

更新:我有这样做的一个功能,该功能使这一结果:

public static List<TResult> GetSingleColumn<T, TResult>(Func<T, bool> predicate, Func<T, TResult> select) where T : class 
{ 
    using (var db = new DBModelDataContext()) 
    { 
     var q = db.GetTable<T>().AsQueryable(); 
     if (predicate != null) 
      q = q.Where(predicate).AsQueryable(); 
     return q.Select(select).ToList(); 
    } 
} 

,并使用它像这样:

var ids = DBMH.GetSingleColumn<Customer, int>(null, c => c.ID); 

回答

2
public static List<TResult> GetSingleColumn<T, TResult>(
    Expression<Func<T, bool>> predicate, 
    Expression<Func<T, TResult>> select) where T : class 
    { 
    using (var db = GetData()) 
    { 
    var q = db.GetTable<T>().AsQueryable(); 
    if (predicate != null) 
    q = q.Where(predicate).AsQueryable(); 
    var q2 = q.Select(select); 
    return q2.ToList(); 
    } 
    } 

这是你应该做的方式。

+0

太棒了!多谢,伙计。 – 2013-06-08 09:36:38

4

如果你只选择你需要的字段它会缩小结果SQL查询的范围。试试这个:

var ids = from customer in db.Customers 
      select customer.ID; 
+0

这段代码是正确的,但我的更新呢? – 2010-05-26 06:50:16

1

Fix'd!

public static List<TResult> GetSingleColumn<T, TResult> 
(
    Expression<Func<T, bool>> predicate, 
    Expression<Func<T, TResult>> select) where T : class 
{ 

既然你使用Func实例,而不是Expression情况下,你使用Enumerable.WhereEnumerable.Select代替Queryable.WhereQueryable.Select。这会导致本地解析,而不是数据库端 分辨率。