C# 显示两列

C# 显示两列,c#,C#,这是一个SL/WPF应用程序,试图显示两列。以下代码: MyDomainContext context = new MyDomainContext(); dataGrid1.ItemsSource = context.DBTables; context.Load(context.GetTwoDataBasesQuery()) ) domainservice.cs包含如下方法定义: public IQueryable<DBTable>GetTwoDataBases() {

这是一个SL/WPF应用程序,试图显示两列。以下代码:

MyDomainContext context = new MyDomainContext();
dataGrid1.ItemsSource = context.DBTables;
context.Load(context.GetTwoDataBasesQuery())
)

domainservice.cs包含如下方法定义:

public IQueryable<DBTable>GetTwoDataBases()
  {
    return this.ObjectContext.DBTables;
  }
public IQueryableGetTwoDataBases()
{
返回this.ObjectContext.DBTables;
}
此代码工作正常,但返回上下文中的所有列 我只需要返回两列,因此更改如下

public IQueryable<DBTable>GetTwoDataBases()
  {
      //trying to return columns
      return GetDBTables().Select(m => new { m.col1, m.col2 });                           
  }
public IQueryableGetTwoDataBases()
{
//正在尝试返回列
返回GetDBTables().Select(m=>new{m.col1,m.col2});
}
但编译器生成错误,不接受“返回”

以下错误无法隐式转换类型 “System.Linq.IQueryable”到 “System.Linq.IQueryable”。明确的 存在转换

如何仅返回两列? 许多thanX

您返回的是匿名类型,但您拥有的集合的返回类型是
DBTable
。您可以创建返回类型
对象
,或者定义一个新的
,并创建该类的对象

将对象设为返回类型

或者,返回IQueryable而不是匿名类型

public IQueryableGetTwoDataBases()
{
//尝试重新运行列
返回GetDBTables()
.Select(m=>newyourcustomtype{YourCustomTypeProperty1=m.col1,YourCustomTypeProperty2=m.col2});
}
public object GetTwoDataBases()
{
     //trying to retrun columns
     return GetDBTables().Select(m => new { m.col1, m.col2 });    
}
public IQueryable<YourCustomType>GetTwoDataBases()
{
     //trying to retrun columns
     return GetDBTables()
            .Select(m => new YourCustomType { YourCustomTypeProperty1 = m.col1, YourCustomTypeProperty2 = m.col2 });    
}