Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在列表中填写匿名类型?_C#_.net_Linq_Linq To Sql_Anonymous Types - Fatal编程技术网

C# 如何在列表中填写匿名类型?

C# 如何在列表中填写匿名类型?,c#,.net,linq,linq-to-sql,anonymous-types,C#,.net,Linq,Linq To Sql,Anonymous Types,我试图通过以下代码编写一些关于从匿名类型生成列表的代码: public static List<T> MakeList<T>(T itemOftype) { List<T> newList = new List<T>(); newList.Add(itemOftype); return newList; } 我看不出你的扩展方法有什么意义,因为已经有一个ToList扩展方法,它将创建一个anymous类型的列

我试图通过以下代码编写一些关于从匿名类型生成列表的代码:

public static List<T> MakeList<T>(T itemOftype)
{
    List<T> newList = new List<T>();
    newList.Add(itemOftype);
    return newList;
}

我看不出你的扩展方法有什么意义,因为已经有一个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;
}
可以更容易:

Qry.ToList();

更糟糕的是,MakeList方法只返回一个包含单个项的列表,该项由itemOftype变量传递给该列表
SetCalculatedTaskField.MakeList(Qry)
将返回一个包含一个项目的列表,其中包含
Qry
,而不会将
Qry
作为列表返回。
SetCalculatedTaskField.MakeList(Qry)
Qry.ToList();