2016-12-07 165 views
0

我有一个字符串(q.ADDLOption)与价值观一样的下拉列表选项

Select,|IE,IE|Safari,Safari|Chrome,Chrome|  

解析字符串我想要解析它是在一个下拉列表中的选项

Optionddl oddl = q.ADDLOption.Split('|').ToList<Optionddl>(); <== this is giving error 

我还有类

public class Optionddl 
{ 
    public string text { get; set; } 
    public string value { get; set; } 
} 
+0

什么错误那youre得到些什么? –

+0

,你可以给我们提供更多的代码,因为这不是很多帮助你,什么是q? –

+0

使用'列表 oddl = q.Trim('','|')。Split('|')。Select(x => new Optionddl {text = x.Trim().Split(',')[0 ],value = x.Trim().Split(',')[1]})。ToList();' –

回答

1

这可能与代码做的伎俩为您

List<Optionddl> oddl = q.ADDLOption.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries) 
         .Select(x => new Optionddl 
         { 
          text = x.Split(',')[0], 
          value = x.Split(',')[1] 
         }) 
         .ToList<Optionddl>(); 

的第一个问题是q.ADDLOption.Split.ToList会返回一个列表,而不是Optionddl的对象。其次,我们不能直接将字符串[]的数组转换为List,因为'string []'不包含'ToList'的定义,而最好的扩展方法是重载'System.Linq.Enumerable.ToList(System.Collections.Generic.IEnumerable )'有一些无效的参数将是错误。最后,创建ToListToList<Optionddl>是可选的。

希望这有助于

0

因为Optionddl是不是可以转换为一个List。 考虑一下:

List<Optionddl> oddl = q.ADDLOption.Split(new string[]{'|'}).ToList<Optionddl>(); 
+0

不幸的是,这不会编译。 'char'不能隐式转换为'string' –

0

另外,您可以创建一些隐性/明确的运营商:

public class Optionddl 
{ 
    public string text { get; set; } 
    public string value { get; set; } 

    public static implicit operator string(Optionddl option) 
    { 
     return option.text + "," + option.value; 
    } 

    public static implicit operator Optionddl(string str) 
    { 
     string[] extracted = str.Split(","); 
     return new Optionddl { text = extracted[0], value = extracted[1] }; 
    } 
} 

这种方式可以使这样的:

Optionddl meOption = new Optionddl { value = "IE", text = "IE" }; 
string meOptionString = meOption; // result of meOptionString = "IE,IE" 
meOption = meOptionString; // result of meOption = { text = "IE", value = "IE" }