Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.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# 如何执行LINQ查询和选择?_C#_Linq - Fatal编程技术网

C# 如何执行LINQ查询和选择?

C# 如何执行LINQ查询和选择?,c#,linq,C#,Linq,我正在运行以下程序: var abc = new adminModel(); string text = abc.AnswerType.SingleOrDefault(s => s.Value == "2"); string text0 = abc.AnswerType.Single(s => s.Value == "2").Text; var text1 = (from a in abc.AnswerType here a.Value == "2" select a.Te

我正在运行以下程序:

var abc = new adminModel();
string text = abc.AnswerType.SingleOrDefault(s => s.Value == "2");
string text0 = abc.AnswerType.Single(s => s.Value == "2").Text;
var text1 = (from a in abc.AnswerType 
  here a.Value == "2"
  select a.Text).SingleOrDefault();
其中AnswerType如下所示:

public class adminModel
{

    public IEnumerable<SelectListItem> AnswerType
    {
        get
        {
            return new[]
                {
                    new SelectListItem { Value = "1", Text = "1 answer" },
                    new SelectListItem { Value = "2", Text = "2 answers" },
                    new SelectListItem { Value = "3", Text = "3 answers" },
                    new SelectListItem { Value = "4", Text = "4 answers" },
                    new SelectListItem { Value = "5", Text = "5 answers" },
                    new SelectListItem { Value = "6", Text = "6 answers" },
                    new SelectListItem { Value = "7", Text = "7 answers" },
                };
        }
    }

}
公共类管理员模型
{
公共IEnumerable应答类型
{
得到
{
返回新的[]
{
新建SelectListItem{Value=“1”,Text=“1 answer”},
新建SelectListItem{Value=“2”,Text=“2答案”},
新建SelectListItem{Value=“3”,Text=“3答案”},
新建SelectListItem{Value=“4”,Text=“4答案”},
新建SelectListItem{Value=“5”,Text=“5答案”},
新建SelectListItem{Value=“6”,Text=“6答案”},
新建SelectListItem{Value=“7”,Text=“7答案”},
};
}
}
}

但我收到一条错误消息,说“无法将SelectListItem转换为字符串”。有没有一种方法可以直接从SelectedListItem中提取文本?

在您的代码
应答类型中。SingleOrDefault(s=>s.Value==“2”)
将返回
SelectedListItem
实例,而不是
字符串

如果需要获取文本,查询将是:

string text = AnswerType.Single(s => s.Value == "2").Text;

试试这个:

string text = AnswerType
        .Where(s => s.Value == "2")
        .Select(s=> s.Text)
        .SingleOrDefault();

这将返回错误只能将赋值、调用、递增、递减和新对象表达式用作statement@DavidH-我用
AnswerType
复制/粘贴您的代码并选中<代码>文本
分配了
2个答案
字符串。这可能是我使用AnswerType的方式。我将在我的问题中添加一些东西来说明这一点。@David H-我看到了你的更新。再次复制/粘贴代码。注释了
主题
子主题
,因为它们未定义。运行代码并
abc.AnswerType.Single(s=>s.Value==“2”)。Text
返回
2个答案。我为问题添加了更多细节。也许这就是我设置回答类型的方式?
string text = AnswerType
        .Where(s => s.Value == "2")
        .Select(s=> s.Text)
        .SingleOrDefault();