2012-04-11 52 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