无法将类型'int'隐式转换为'System.Collections.Generic.List <QuickTest.Stock>'

mst*_*agg 7 c# linq collections list

我有以下代码:

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Stock是一个具有字符串属性TickerSymbol和Name的对象.它还具有双重属性Price,ChangeDollars和ChangePercent.

我写的第二个LINQ语句是在消息中抛出错误,"不能将类型'int'隐式转换为'System.Collections.Generic.List'".我很困惑'int'类型来自何处以及如何修复此错误,因为我不在程序中的任何位置使用任何int值.

我对LINQ也很新,这是我第一次使用它.这个错误很可能是LINQ的一些复杂性的结果,我不知道.

任何人都知道为什么会发生这种错误以及如何解决它?

Chr*_*tos 11

你得到的错误是合理的,因为RemoveAll返回被移除的股票的数量.这是一个整数.然后尝试将此赋值给被调用的变量ticker,该变量包含类型对象的列表Stock.

你可能想要的是去除所有的股票,他们TickerSymbolgm然后写他们已留在股票到控制台的股票.为此,您可以尝试这样做:

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

foreach (Stock s in ticker)
{
    Console.WriteLine(s.Name);
}
Run Code Online (Sandbox Code Playgroud)

此外,对于记录,如MSDN中所述:

方法 List<T>.RemoveAll()

删除与指定谓词定义的条件匹配的所有元素.

它的签名如下:

public int RemoveAll(Predicate<T> match)
Run Code Online (Sandbox Code Playgroud)

Predicate<T>是一个方法的委托,如果传递给它的对象与委托中定义的条件匹配,则返回true.当前List的元素分别传递给Predicate委托,匹配条件的元素将从List中删除.

该方法执行线性搜索; 因此,此方法是O(n)操作,其中n是List的Count属性.