2017-05-28 66 views
0

除了我有一个更复杂的类(具有多个属性)之外,我想要做的与此类似。将一个类的属性序列化为一个单独的字符串

Convert a list to a string in C#

我有多重属性的类存储在一个列表

虽然填充这个名单,我也填充|分隔字符串名称属性,它随后被正则表达式

所以,我可以只填充列表,然后,轻松地从列表中的类的Name属性中构建一个|分隔的字符串?

示例代码

类被填充:

public class Thing 
{ 
    public MyParentClass parent; 
    public string Name;   
    public List<string> OtherThings = new List<string>(); 

    public Thing(string path) 
    { 
     // Here I set the Name property to the filename 
     Name = Path.GetFileNameWithoutExtension(path); 
    } 

} 

填充代码:

public List<Thing> Stuff = new List<Thing>(); 
public string AllThings = ""; 

void GetThings(files) 
{ 
foreach (string f in files) 
    { 
     Stuff.Add(f) 
     AllThings = AllThings + Path.GetFileNameWithoutExtension(f) + "|"; 
    } 
} 

所以,我想知道的是:我可以删除AllThings = AllThings +线,而是填充AllThings后所有的类都加载了?

如果我尝试这样:

AllCubes = string.Join("|", Stuff.ToArray()); 

我得到

CS0121的调用是以下的方法或 性能之间暧昧:“的string.join(字符串,params对象[] )”和 '的string.join(字符串,IEnumerable的)'

这是毫无惊喜,因为我知道这是不是SIMP le - 我只是想试试看

回答

1

要使String.Join工作,您将需要提供字符串的集合,而不是自定义类型。

模糊性是由于协方差造成的,因为在这种情况下,它可以隐含地变为objectstring

所以不是你的方法有明确说明,这将是string和推object一定的财产作为string继续:

AllCubes = string.Join("|", Stuff.Select(x => x.Name));

这将提供IEnumerablestrings,它符合合同要求IEnumerable<string>

+0

非常好。那是'LINQ'吧? –

+0

@ Nick.McDermaid是的,它当然是。 – Karolis

相关问题