日期:2014-05-18  浏览次数:20725 次

List的扩展方法Where问题
有如下两段代码
1.
C# code

            ChannelInfo channel=null;
            foreach (ChannelInfo item in _channelInfo)
            {
                if (item.Key == key)
                {
                    channel=item;
                    break;
                }
            }


2.
C# code
ChannelInfo channel = _channelInfo.Where(s => s.Key == key).First();


我的理解是 因为Where方法是取整个列表中符合要求的数据,然后First取第一个,这样的效率和第一个比起来,是第一个效率高吗?




------解决方案--------------------
ChannelInfo channel = _channelInfo.FirstOrDefault(s => s.Key == key);
你如果只想获取第一个,没必要用WHERE 直接FirstOrDefault即可
效率方面,半斤八两,都需要循环遍历
------解决方案--------------------
ChannelInfo channel = _channelInfo.Where(s => s.Key == key).First();

这个要小心没找到,返回null,最好用FirstOrDefault.