尝试使用string.Join连接一个IList

4
我正在尝试将第一个示例http://www.dotnetperls.com/convert-list-string实现到我的方法中,但我很难匹配方法的第二个参数:
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接口也都是用IEnumerable实现的(除非有人要求列出来,否则不在此列举)。
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(",", test);" 可以解决问题,但在我打勾并关闭之前,出现了以下输出:

"Ilistprac.Location, Ilistprac.Location, Ilistprac.Location"

不知道为什么会输出这个,而不是列表中的内容。

4个回答

6

你根本不需要使用ToArray()(因为看起来你正在使用 .Net 4.0),因此你可以直接调用

string.Join(",", test);

刚刚在回答这个问题之前,我的输出结果是:"Ilistprac.Location, Ilistprac.Location, Ilistprac.Location",而不是列表中的项目。原因不明。 - nhat
你没有在你的“位置”对象上重写ToString()方法,所以你得到了默认的行为。 - dlev
@dlev - 这是什么意思,没有在对象上重写ToString()?答案并未提及重写ToString()。你该如何解决这个问题? - Rani Radcliff

2
你需要在 ToArray<Location> 后面加上括号 ()
string printitout = string.Join(",", test.Select(location => location.Site).ToArray()); 

啊,Lambda表达式我不太擅长,但我正在努力学习!这实际上也正确地输出了IList中的内容。 - nhat

2
如果您的Locaions类型实现了IEnumerable,则不需要使用ToArray
string printiout = String.Join(",", test);

1

尝试:

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

3
谢谢回复。我收到了这个错误信息:"The call is ambiguous between the following methods or properties: 'string.Join<Ilistprac.Location>(string, System.Collections.Generic.IEnumerable<Ilistprac.Location>)' and 'string.Join(string, params object[])'"。 - nhat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接