加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 无法将类型’int’隐式转换为’System.Collections.Generi

发布时间:2020-12-15 08:04:41 所属栏目:百科 来源:网络整理
导读:我有以下代码: static void Main(string[] args) { ListStock ticker = new ListStock(); 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 i
我有以下代码:
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是一个具有字符串属性TickerSymbol和Name的对象.它还具有双重属性Price,ChangeDollars和ChangePercent.

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

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

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

解决方法

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

你可能想要的是删除他们的TickerSymbol是gm的所有股票,然后将他们留在股票代码中的股票写入控制台.为此,您可以尝试这样做:

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

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

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

方法List< T> .RemoveAll()

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

它的签名如下:

public int RemoveAll(Predicate<T> match)

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读