如何填写匿名类型列表?
问题描述:
我尝试写一些代码通过下面的代码有关生成匿名类型列表:如何填写匿名类型列表?
public static List<T> MakeList<T>(T itemOftype)
{
List<T> newList = new List<T>();
newList.Add(itemOftype);
return newList;
}
但返回错误。我:
通过 KeyFieldName属性指定一个主键字段中找不到 底层数据源。确保 字段名拼写正确。 注意字符大小写。
Main.cs
var Qry = from tableRaletions in taskMaints.TaskRelations
where tableRaletions.TaskId == Convert.ToInt32(txtID.Text) && tableRaletions.RelTypeId == 12
select new
{
tableRaletions.RefMaintenance.code,
tableRaletions.RefMaintenance.shortdesc
};
GridMaintenanceData.DataSource = SetCalculatedTaskField.MakeList(Qry);
GridMaintenanceData.DataBind();
答
我没有看到你的扩展方法的点作为已经有一个ToList扩展方法,这将创建anymous类型的列表,你的方法会做的是创建一个列表,其中的一个项目是您的匿名类型的IQueryable。其次,错误是说GridMaintenanceData有一个名为KeyFieldName的属性,并且在那里指定了一个字段名,它不在绑定到它的数据源中,可能是因为你的愚蠢的MakeList方法。
而是执行此操作:
var Qry = from tableRaletions in taskMaints.TaskRelations
where tableRaletions.TaskId == Convert.ToInt32(txtID.Text) && tableRaletions.RelTypeId == 12
select new
{
tableRaletions.RefMaintenance.code,
tableRaletions.RefMaintenance.shortdesc
};
GridMaintenanceData.DataSource = Qry.ToList();
GridMaintenanceData.DataBind();
答
你已经指定了一个不是在你的数据源存在KeyFieldName。究竟错误在说什么。就我的例子而言,这与通用列表的数量无关。
从你的例子中,我猜你的主键是RelationId
而你的KeyFieldName
被设置为该属性。因此,只要改变确保RelationId是回报您的选择:
select new
{
tableRaletions.RefMaintenance.RelationId // It's spelt `relations` by the way.
tableRaletions.RefMaintenance.code,
tableRaletions.RefMaintenance.shortdesc
};
答
这里是你的代码:
public static List<T> MakeList<T>(T itemOftype)
{
List<T> newList = new List<T>();
newList.Add(itemOftype);
return newList;
}
你不直接使用什么List<T>
? MakeList<T>
的目的是什么?而
SetCalculatedTaskField.MakeList(Qry)
可以更容易:
Qry.ToList();
我试图从任何类返回列表值,但我必须列出定义... –
Penguen
2010-08-13 10:30:38
更糟糕的是比MakeList方法简单地返回一个列表包含itemOftype变量传递给它的单个项目。 'SetCalculatedTaskField.MakeList(Qry)'将返回一个列表,其中包含一个带有'Qry'的项目,它不会返回'Qry'作为列表。 – 2010-08-13 13:20:37