简体   繁体   中英

How to convert string to double in C#

In the following code , rating in generating error

string[] allLines = File.ReadAllLines(@"Ratings.csv");

var parsed = from line in allLines
            let row = line.Split(';')
             select new
             {
                 UserId = row[0],
                 ItemId = row[1],
                 rating = row[3]
            };
var Rating = parsed.Select(x => new AddRating (x.UserId, x.ItemId,x.rating));

client.Send(new Batch(Rating));


var detailViews = parsed.Select(x => new AddDetailView(x.UserId, x.ItemId,x.rating ));
String st = "85.78";
Double db = Convert.ToDouble(st);

//Or With Error Hndler

try
        {
            string st = "85.78";
            Double db = Convert.ToDouble(st);
        }
catch (FormatException)
        {

            // Your error handler 

        }

The exception is telling you what the issue is. Your constructor is expecting doubles, and you're passing it strings. In order to fix it, you've gotta parse your string inputs into doubles.

The way your code is written, you'll have to change the way you're using the .Select statement in order to parse it in a decent error handling manner.

I'd suggest swapping the .Select for a foreach , then parsing each property, then instantiating your class.

foreach (var item in parsed)
{
    double userId = 0;
    double itemId = 0;
    double rating = 0;
    double.TryParse(item.UserId, out userId);
    double.TryParse(item.ItemId, out itemId);
    double.TryParse(item.rating, out rating);

    var rating = new AddRating(userId, itemId, rating);
    //**** do whatever you want with the new object
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM