2012-04-11 33 views
2

我想要實現的第一個例子http://www.dotnetperls.com/convert-list-string到我的方法,但我有一個很難匹配該方法的第二個參數:嘗試的string.join一個IList

string printitout = string.Join(",", test.ToArray<Location>); 

錯誤消息:

The best overloaded method match for 'string.Join(string, 
System.Collections.Generic.IEnumerable<string>)' has some invalid arguments 

所有的IList接口都是用IEnurmerable實現的(除非有人要我,否則這裏沒有列出)。

class IList2 
{ 
    static void Main(string[] args) 
    { 

    string sSite = "test"; 
    string sSite1 = "test"; 
    string sSite2 = "test"; 

    Locations test = new Locations(); 
    Location loc = new Location(); 
    test.Add(sSite) 
    test.Add(sSite1) 
    test.Add(sSite2) 
    string printitout = string.Join(",", test.ToArray<Location>); //having issues calling what it needs. 

    } 
} 
string printitout = string.Join(",", test.ToArray<Location>); 


public class Location 
{ 
    public Location() 
    { 

    } 
    private string _site = string.Empty; 
    public string Site 
    { 
     get { return _site; } 
     set { _site = value; } 
    } 
} 

public class Locations : IList<Location> 
{ 
    List<Location> _locs = new List<Location>(); 

    public Locations() { } 

    public void Add(string sSite) 
    { 
     Location loc = new Location(); 
     loc.Site = sSite; 
     _locs.Add(loc); 
    } 
} 

編輯: 確定使用 「的string.join(」, 「測試);」工作,我關閉在此之前有一個對勾,由於某種原因,我的輸出,輸出:

「Ilistprac.Location,Ilistprac.Location,Ilistprac.Location」

出於某種原因,而不是什麼在列表中。

嘗試

回答

4

你不需要ToArray()在所有的(因爲它似乎你正在使用.NET 4.0),這樣你就可以撥打電話

string.Join(",", test); 
+0

啊是的,我使用4.0,工作。 – nhat 2012-04-11 19:27:04

+0

就在我回答這個問題之前。我的輸出結果如下:「Ilistprac.Location,Ilistprac.Location,Ilistprac.Location」,而不是出於某種原因列表中的列表項。 – nhat 2012-04-11 19:32:55

+0

你沒有覆蓋你的'Location'對象的'ToString()',所以你得到了默認的行爲。 – dlev 2012-04-11 19:41:52

1

string printitout = string.Join(",", test); 
+3

感謝您的答覆,我得到這樣的錯誤消息:調用以下方法或屬性之間曖昧:「 string.Join (字符串,System.Collections.Generic.IEnumerable )'和'string.Join(字符串,params對象[])' – nhat 2012-04-11 19:21:42

2

你需要把括號 - () - 後ToArray<Location>

string printitout = string.Join(",", test.Select(location => location.Site).ToArray()); 
+0

確定它幾乎工作,但我得到錯誤上面列出的消息 – nhat 2012-04-11 19:23:40

+0

@nhat - 修正了上面的問題。 – DaveShaw 2012-04-11 19:27:30

+0

ah lambda,我不擅長這一點,但我正在努力學習它!這實際上也輸出了IList中的什麼。 – nhat 2012-04-11 19:35:16

2

如果您Locaions類型實現IEnumerable你不需要ToArray

string printiout = String.Join(",", test); 
+0

謝謝你的作品! – nhat 2012-04-11 19:27:53