list <class> .Select throws System.FormatException异常</class>

时间:2013-12-07 12:53:53

标签: c# asp.net

代码抛出(System.FormatException:输入字符串的格式不正确。)excption,有什么问题?

设计师班级

public class designer
{
    public string name { get; set; }
    public string category { get; set; }
}

getData.aspx Page

List<designer> lst = DataAccess.GetDesigners();
return String.Join(",", lst.Select(x => String.Format("{ label: \"{0}\", category: \"{1}\" }", x.name, x.category)));

我需要像这样返回代码

 [
            { label: "anders", category: "People" },
            { label: "andreas", category: "People" },
            { label: "antal", category: "People" }
          ]

2 个答案:

答案 0 :(得分:1)

您的代码的问题在于您在格式字符串中使用{,因此要转义{,应该跟{后跟}后跟{ }

lst.Select(x => String.Format("{{ label: \"{0}\", category: \"{1}\" }}", x.name, x.category));

请记住:使用{}时应转义括号string.Format

答案 1 :(得分:0)

看起来像

var lst = DataAccess.GetDesigners().Where(x => x != null);

保护您免受此异常