C# Convert String to Integer

2020-05-09 10:45发布

问题:

I have finally taken the jump from VB.net to C# so I'm still having some issues. I am making a simple weather app that connects through a RSS feed. I want it to return a label that determines if it is freezing outside, however; I am having issues converting the temperature string to an integer so I can determine if the temperature is less than or equal to 32 degrees. Any ideas?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace WeatherApp
{
    public partial class frmWeather : Form
    {
        string Temperature;
        public frmWeather()
        {
            InitializeComponent();
        }
        private void getWeather()
        {
            string query = string.Format("http://weather.yahooapis.com/forecastrss?w=" + txtZip.Text);
            XmlDocument wData = new XmlDocument();
            wData.Load(query);
            XmlNamespaceManager manager = new XmlNamespaceManager(wData.NameTable);
            manager.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
            XmlNode channel = wData.SelectSingleNode("rss").SelectSingleNode("channel");
            XmlNodeList nodes = wData.SelectNodes("/rss/channel/item/yweather:forecast", manager);
            Temperature = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["temp"].Value;
        }
        private void tmrWeather_Tick(object sender, EventArgs e)
        {
            getWeather();
            DateTime now = DateTime.Now;
            lblTemp.Text = "" + Temperature;
            if (lblTemp.Text <= "32")
            {
                lblResult.Text = "It is freezing outside!";
            }
        }
    }
}

回答1:

You can use Convert.ToInt32() method to convert your String into integer

Try This:

      //lblTemp.Text = "" + Temperature;  this statement is not required.
      if (Convert.ToInt32(Temperature) <= 32)
        {
            lblResult.Text = "It is freezing outside!";
        }

OR

you can use int.TryParse() method to perform the proper conversion even if the data is invalid.

Try This:

        int temp;
        if (int.TryParse(Temperature,out temp))
        {
             if(temp <= 32)             
             lblResult.Text = "It is freezing outside!";
        }


回答2:

Convert it to integer,then compare with 32 ?

if (Convert.ToInt32(lblTemp.Text) <= 32)

Or just use Temperature variable which is an integer

if(Convert.ToInt32(Temperature) <= 32)

This line is pointless:

lblTemp.Text = "" + Temperature;

You might want to define Temperature as integer or double.



回答3:

Another valid method would be

int temp = 0;
if (int.TryParse(lblTemp.Text, out temp))
{
     lblResult.Text = temp < 32 ? "It's freezing outside" : "Not yet freezing";
}
else
{
    // parsing error
}

Convert.ToInt() and int.parse() will also work, but int.TryParse() also guards you against exceptions in case the lblTemp.Text does not contain a valid integer. All of these methods, however, solve your initial problem, i.e. once you parse the string into a number, you can compare them to a fix value.



回答4:

If temperature is integer, then don't use string to keep it's value. Keep temperature as integer (or double) type:

int Temperature;

And use it to compare with integer value 32:

private void tmrWeather_Tick(object sender, EventArgs e)
{
    getWeather();
    DateTime now = DateTime.Now;
    lblTemp.Text = Temperature.ToString();

    if (Temperature <= 32)        
        lblResult.Text = "It is freezing outside!";        
}

Also I suggest you to use Linq to Xml for parsing:

XDocument xdoc = XDocument.Load(query);
XNamespace yweather = "http://xml.weather.yahoo.com/ns/rss/1.0";
Temperature = (int)xdoc.Descendants("rss")
                       .Elements("channel")
                       .Elements("item")
                       .Element(yweather + "forecast")
                       .FirstOrDefault();

If you don't want to change your implementation, then simply parse temp value:

string temp = channel.SelectSingleNode("item")
                     .SelectSingleNode("yweather:condition", manager)
                     .Attributes["temp"].Value;
Temperature = Int32.Parse(temp);

NOTES: I suggest you to make int GetTemperature() method instead of void getWeather() method, because method name tells that it's query method which should return some value instead of changing class state (probably you will not need Temperature field in this case). Also instead of hard-coded value 32 create some constant integer value with name which describes what 32 means. And finally - use Capitalization Styles suggested by Microsoft.