Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.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
将Linq查询结果返回到列表对象(基于条件)_Linq - Fatal编程技术网

将Linq查询结果返回到列表对象(基于条件)

将Linq查询结果返回到列表对象(基于条件),linq,Linq,我需要基于外键值将大量Linq查询结果返回到列表对象中。这样做的语法是什么?我是新使用Linq的,所以下面是我到目前为止最好的猜测。我在.Where()“子句”中收到一个错误,指出“当前上下文中不存在名称'pt'。如有任何帮助,将不胜感激 List<AgentProductTraining> productTraining = new List<AgentProductTraining>(); var prodCodes = produc

我需要基于外键值将大量Linq查询结果返回到列表对象中。这样做的语法是什么?我是新使用Linq的,所以下面是我到目前为止最好的猜测。我在.Where()“子句”中收到一个错误,指出“当前上下文中不存在名称'pt'。如有任何帮助,将不胜感激

        List<AgentProductTraining> productTraining = new List<AgentProductTraining>();

        var prodCodes = productTraining.Select(pt => new[]
                                                         {
                                                             pt.ProductCode,
                                                             pt.NoteId,
                                                             pt.ControlId
                                                         })
                                                         .Where(pt.CourseCode == course.CourseCode);
List productTraining=new List();
var prodCodes=productTraining.Select(pt=>new[]
{
产品代码,
pt.NoteId,
控制ID
})
.其中(pt.CourseCode==course.CourseCode);

如果使用扩展方法,则需要切换where的位置并选择:

var prodCodes = productTraining.Where(pt => pt.CourseCode == course.CourseCode)
                               .Select(pt => new SomeRandomType
                                                         {
                                                             ProductCode = pt.ProductCode,
                                                             NoteId = pt.NoteId,
                                                             ControlId = pt.ControlId
                                                         });
正如您在上面看到的,我还建议您为select语句创建一个类型,这样您就不会依赖匿名类型。您应该将其放入一个您了解所有信息的对象类型中


另外,如果CourseCode是一个字符串,那么它应该是
pt.CourseCode.Equals(course.CourseCode)

Hm…只要我定义了某个随机类型(我已经尝试了string和AgentProductTraining),它立即开始对ProductCode、NoteId和ControlId抛出错误。消息说:“ProductCode”在当前上下文中不存在,“NoteId”不存在…等等。这是因为您需要创建一个包含这些字段的新对象类。这样做可以避免使用匿名类型的危险。有什么方法可以做到这一点吗不创建新的对象类?我只需要为程序的这一部分使用它,因此仅为此创建一个新的类库似乎有点麻烦。您可以通过删除上面的SomeRandomType来使用匿名类型。我会自动创建一个对象类,这样我就不必担心使用匿名类型。