简体   繁体   English

如何在Linq中获得多个专栏

[英]How to get more than one column in Linq

here is my code: 这是我的代码:

firstAnswer = p.Answers.Select(z => z.vountcount, z.isSelected).FirstOrDefault()

In the select statement, it returns a syntax error. 在select语句中,它返回语法错误。 I am trying to get more then one column. 我试图获得更多的专栏文章。

var firstAnswer = p.Answers.FirstOrDefault().Select(new { VountCount = z.vountcount, IsSelected = z.isSelected });

You must specify a type . 您必须指定类型 Var is the keyword allowing you to instantiate an anonymous type . Var是允许您实例化匿名类型的关键字。

You'll either have to create a type or use anonymous types to capture that result: 您要么必须创建一个类型,要么使用匿名类型来捕获该结果:

Anonymous types: 匿名类型:

var firstAnswer = p.Answers.Select(z => new { vountcount = z.vountcount, isSelected = z.isSelected }).FirstOrDefault();

The explicit naming is in most cases optional. 在大多数情况下,显式命名是可选的。 Using the var keyword here ensures, that you can assign that anonymous result. 在此处使用var关键字可确保您可以分配该匿名结果。 If you want to hand that result to some method, it'll get difficult with anonymous types. 如果您想将结果传递给某种方法,匿名类型将很困难。

Dedicated type: 专用类型:

public class ReducedAnswer
{
    public int vountcount { get; set; }
    public bool isSelected { get; set; }

    public ReducedAnswer()
    {
    }
}

ReducedAnswer firstAnswer = p.Answers.Select(z => new ReducedAnswer { vountcount = z.vountcount, isSelected = z.isSelected }).FirstOrDefault();

Kept it close to typical LINQ model classes and your naming. 保持它接近典型的LINQ模型类和您的命名。 Note the use of the type in front of firstAnswer . 注意firstAnswer前面类型的使用。 You could go with var here as well. 您也可以在这里使用var

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM