2013-03-04 2 views
0

C#의 목록에서 문자열을 가져 오려고하지만이를 수행 할 방법을 찾을 수 없습니다. Heres는 내 코드C# 목록에서 문자열 가져 오기

public class CurrentCondition 
{ 
    public string cloudcover { get; set; } 
    public string humidity { get; set; } 
    public string observation_time { get; set; } 
    public string precipMM { get; set; } 
    public string pressure { get; set; } 
    public string temp_C { get; set; } 
    public string temp_F { get; set; } 
    public string visibility { get; set; } 
    public string weatherCode { get; set; } 
    public List<WeatherDesc> weatherDesc { get; set; } 
    public List<WeatherIconUrl> weatherIconUrl { get; set; } 
    public string winddir16Point { get; set; } 
    public string winddirDegree { get; set; } 
    public string windspeedKmph { get; set; } 
    public string windspeedMiles { get; set; } 
} 
    public class Data 
{ 
    public List<CurrentCondition> current_condition { get; set; } 
} 

내가, 예를 들어, current_condition 목록에서 temp_F 문자열을 얻을합니다. 어떻게해야합니까? current_condition 이후

+2

Data라는 클래스가 있습니까? 정말? –

+0

적어도 우리에게 몇 가지 실패 시도를 보여 줘야합니다 – Jorge

+0

@MitchWheat yea 정말로 그 이름을 바꿔야합니다 –

답변

2

는. 목록, 당신은 당신이에 관심이있는 목록 인덱스 알고 있어야 당신이 인덱스 0, 당신은 당신이 CurrentCondition의 목록에서 모든 온도를 원하는 가정

Data data = new Data(); 
// Some code that populates `current_condition` must somehow run 
string result = data.current_condition[0].temp_F. 
3

를 작성합니다 싶은 말 인스턴스는, 당신은 쉽게 Linq를 사용하여이 작업을 수행 할 수 있습니다 :

List<string> temps = current_condition.Select(x => x.temp_F).ToList(); 

을 허용 대답에 비추어, 여기 Linq에있는 특정 온도 얻는 방법은 다음과 같습니다

+0

업데이트 된 답변은 OP가 찾고있는 것을 실제로 제공하지 않으며 받아 들인 대답과 동등하지 않습니다. –

1
List<string> list = new List<string>(); 
current_condition.ForEach(cond => list.Add(cond.temp_F)); 
0

ElementAt (int)를 사용하여 목록의 개체에 액세스 할 수 있습니다.

String t = current_condition.ElementAt(index).temp_F; 
+0

아니면 그냥 배열 인덱스를 사용하지 않으시겠습니까? 'List '을'IEnumerable '처럼 처리 할 필요가 없습니다. 이 해결책은 O (N)이며, 배열 색인을 사용하는 것은 O (1)입니다. –

+0

예. 당신 말이 맞아요. 많은 초보자들이 배열과 같은 목록을 다루는 것과 혼동을 겪었으므로 "긴"버전을 게시하는 것이 더 좋을 것이라고 생각했습니다. 하지만 코드가 빠릅니다. – Fred

관련 문제