日期:2014-05-20  浏览次数:20944 次

select 返回值问题 (LINQ)
刚开始学linq,所以对他还不是很熟悉,说下我的问题:
如果我查询的时候想返回表中的几个字段,
select id,name;通常返回是List<Type>
那我使用linq该如何写,返回值是什么,

public List<MyCustomer> SelectRecordNames()
  { 
  return (from cust in objDataContext.MyCustomers
  select new { cust.CustomerID, cust.CompanyName, cust.ContactName }).ToList();

  }
我这样写会报错,请问如何该,我前台是想绑定数据,
如果是SQL语句,我想要的是select id,name contactname from customers

------解决方案--------------------
楼主如果只是想访问三个字段的list,则需要显式定义其类型,不能使用new一个匿名类型的方式
可以参考
class BaseCustomer
{
属性 CustomerID,
属性 CompanyName
...
}

public List <BaseCustomer> SelectRecordNames()
{
return (from cust in objDataContext.MyCustomers
select new BaseCustomer(){ CustomerID=cust.CustomerID,CompanyName=cust.CompanyName}).ToList();




------解决方案--------------------
试试这个,也许有用
public class partCustomer
{
CustomerID xxxxxxx;
CompanyName xxxxxxx;
ContactName xxxxxxx;
...
}
public List <partCustomer> SelectRecordNames() 

return (from cust in objDataContext.MyCustomers 
select new { cust.CustomerID, cust.CompanyName, cust.ContactName }).ToList(); 

}