如何执行LINQ查询并选择?

时间:2011-06-13 04:07:20

标签: 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.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" },
                };
        }
    }

}

但我收到一条错误消息,指出“无法将SelectListItem转换为字符串”。有没有办法可以从SelectListItem中提取文本?

2 个答案:

答案 0 :(得分:2)

在您的代码中AnswerType.SingleOrDefault(s => s.Value == "2")将返回SelectedListItem个实例,而不是string

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

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

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

答案 1 :(得分:1)

试试这个:

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