Chris Loonam
Chris Loonam

Reputation: 5745

C# get string from list

I am trying to get a string from a list in c#, but can't find a way to do it. Heres my code

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

and I want to get, for example, the temp_F string from the current_condition list. How can I do this?

Upvotes: 0

Views: 16347

Answers (4)

Grant Winney
Grant Winney

Reputation: 66439

Assuming you want all the temperatures from your list of CurrentCondition instances, you could do this easily using Linq:

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

In light of the accepted answer, here's how to get a specific temperature with Linq:

string temp = current_condition.Where(x => x.observation_time == "08:30").FirstOrDefault(x => x.temp_F);

Upvotes: 3

Fred
Fred

Reputation: 3362

You can use ElementAt(int) to access an object in a list.

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

Upvotes: 0

Eli White
Eli White

Reputation: 1024

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

Upvotes: 1

Eric J.
Eric J.

Reputation: 150108

Since current_condition is a list, you would have to know which list index you are interested in. Say you want index 0, you would write

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

Upvotes: 2

Related Questions