2012-04-12 2 views
1

"string.Join (", "test"); 내가 ToString, Convert.ToString 등을 시도하고 난 아직도 그 출력을 얻을string에 시도 중입니다. IList에 조인하고 콘솔에 결과를 출력하십시오.

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

: 작동하지만 어떤 이유로 나는의 출력을 얻을.

모든 IList 인터페이스는 IEnurmerable로 구현됩니다 (누군가가 원한다면 여기에 나열되지 않음).

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

    string sSite = "test"; 

string sBldg = "test32"; 
    string sSite1 = "test"; 
    string sSite2 = "test"; 

    Locations test = new Locations(); 
    Location loc = new Location(); 
    test.Add(sSite, sBldg) 
    test.Add(sSite1) 
    test.Add(sSite2) 
    string printitout = string.Join(",", test); //having issues outputting whats on the list 

    } 
} 
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; 

     loc.Bldg = sBldg; 
     _locs.Add(loc); 
    } 

    private string _bldg = string.Empty; 

    public string Bldg 

    { 

     get { return _bldg; } 

     set { _bldg = value; } 

    } 


} 

답변

3

은 각 요소에 대한 것을 촉구 LocationJoin로에 대한 유용한 ToString 구현을 제공해야합니다. 디폴트의 ​​구현에서는, 형태의 이름을 돌려줍니다. documentation을 참조하십시오.

당신이 유형

class SomeType 
{ 
    public string FirstName { get; private set; } 
    public string LastName { get; private set; } 

    public SomeType(string first, string last) 
    { 
     FirstName = first; 
     LastName = last; 
    } 

    public override string ToString() 
    { 
     return string.Format("{0}, {1}", LastName, FirstName); 
    } 
} 

처럼 당신이이 문자열로 표현하는 방법을 지정할 필요가 그래서 경우. 그렇게하면 string.Join을 사용하여 아래 출력을 생성 할 수 있습니다.

var names = new List<SomeType> { 
    new SomeType("Homer", "Simpson"), 
    new SomeType("Marge", "Simpson") 
}; 

Console.WriteLine(string.Join("\n", names)); 

출력 :

Simpson, Homer 
Simpson, Marge 
+0

, 1 개 이상의 값을 반환하려면 형식화해야합니다. 감사합니다. – nhat

+0

실제로 여러 값을 반환하는 것이 아닙니다. 그것은 당신의 타입을'string'으로 표현하는 방법입니다. 'Join'은 시퀀스에서'Location'의 각 인스턴스에 대해'ToString'을 호출합니다. 클래스의 기본 문자열 표현은 유형 이름입니다. 다른 것을 원하면 타입에 대해'ToString'을 오버라이드 할 필요가 있습니다. –

+0

Gotcha, 기본 구현이 무엇인지 알지 못했고이를 문자열로 가져 오려면 재정의가 필요했습니다. 그 값을 반환하는 문제가 있었지만 트릭을 한 것처럼 형식화했습니다. – nhat

3

당신은 ToString() 당신이 현재의 접근 방식을 유지하려면 몇 가지 의미있는 출력을 제공하기 위해 Location 클래스를 inc를 오버라이드 (override) 예가 : 내가 볼

public override string ToString() 
{ 
    return Site; 
} 
관련 문제