2017-05-28 19 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

相關問題