Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'int' to 'System.Collections.Generic.List<QuickTest.Stock>'

I have the following code:

static void Main(string[] args)
    { 
        List<Stock> ticker = new List<Stock>();
        ticker.Add(new Stock("msft"));
        ticker.Add(new Stock("acw"));
        ticker.Add(new Stock("gm"));

        ticker = ticker.OrderBy(s => s.Name).ToList();

        foreach (Stock s in ticker)
        {
            Console.WriteLine(s.Name);
        }

        Console.WriteLine("\n");
        ticker = ticker.RemoveAll(s => s.TickerSymbol == "gm");

        foreach (Stock s in ticker)
        {
            Console.WriteLine(s.Name);
        }
    }

Stock is an object that has string properties TickerSymbol and Name. It also has double properties Price, ChangeDollars, and ChangePercent.

The second LINQ statement I wrote is throwing an error with the message, "Cannot implicitly convert type 'int' to 'System.Collections.Generic.List'". I am confused as to where the type 'int' is coming from and how to fix this error, as I dont use any int values anywhere in the program.

I am very new to LINQ as well, this is my first time using it. This error could very well be a result of some intricacy of LINQ that I am not aware of.

Anyone know why this error is happening and how to fix it?

like image 449
mstagg Avatar asked Nov 18 '14 16:11

mstagg


1 Answers

It is reasonable the error you get, because RemoveAll returns the number of removed stocks. This is an integer. Then you try to assign this to the variable called ticker, which holds a list of objects of type Stock.

That you probably want is to remove all the Stocks that their TickerSymbol is gm and then write the Stocks that they have been left in ticker to the console. In order to do so, you could just try this:

// This will remove all the stocks you want.
ticker.RemoveAll(s => s.TickerSymbol == "gm");

foreach (Stock s in ticker)
{
    Console.WriteLine(s.Name);
}

Furthermore, for the record, as it is stated in MSDN:

The method List<T>.RemoveAll()

Removes all the elements that match the conditions defined by the specified predicate.

It's signature is the following:

public int RemoveAll(Predicate<T> match)

The Predicate<T> is a delegate to a method that returns true if the object passed to it matches the conditions defined in the delegate. The elements of the current List are individually passed to the Predicate delegate, and the elements that match the conditions are removed from the List.

This method performs a linear search; therefore, this method is an O(n) operation, where n is List's Count property.

like image 70
Christos Avatar answered Oct 26 '22 23:10

Christos