Cannot implicitly convert List' to 

2020-05-10 03:29发布

问题:

Keeps throwing, what is wrong in this part of my code, when I want to return cells I receive this error Cannot implicitly convert type 'System.Collections.Generic.List' to 'double' :

 public double readFileToList(string Path)
    {

        var cells = new List<double>();
        string path = label3.Text;

        if (File.Exists(path))
        {
            double temp = 0;
            cells.AddRange(File.ReadAllLines(path)
                .Where(line => double.TryParse(line, out temp))
                .Select(l => temp)
                .ToList());
            int totalCount = cells.Count();
            cellsNo.Text = totalCount.ToString();

        }

       return cells;

    }

回答1:

It is hard to say for certain without seeing your entire function but my guess would be that you have the return type of your function set to double instead of List<double>. This would cause the error you are seeing.


Edit

Confirmed looking at your edit that this is your problem. Change the return type of your function to List<double> and you will be good to go! Your code should look like this:

public List<double> readFileToList(string Path)
    {

        var cells = new List<double>();
        string path = label3.Text;

        if (File.Exists(path))
        {
            double temp = 0;
            cells.AddRange(File.ReadAllLines(path)
                .Where(line => double.TryParse(line, out temp))
                .Select(l => temp)
                .ToList());
            int totalCount = cells.Count();
            cellsNo.Text = totalCount.ToString();

        }

       return cells;

    }