惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
J
Java Code Geeks
雷峰网
雷峰网
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
V
Vulnerabilities – Threatpost
S
Securelist
The Hacker News
The Hacker News
The Register - Security
The Register - Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Help Net Security
Help Net Security
G
Google Developers Blog
Hugging Face - Blog
Hugging Face - Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
M
MIT News - Artificial intelligence
AI
AI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The GitHub Blog
The GitHub Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Schneier on Security
Schneier on Security
N
Netflix TechBlog - Medium
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
Hacker News - Newest:
Hacker News - Newest: "LLM"
H
Hacker News: Front Page
博客园 - 司徒正美
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
B
Blog
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Security Latest
Security Latest
Engineering at Meta
Engineering at Meta
N
News and Events Feed by Topic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
酷 壳 – CoolShell
酷 壳 – CoolShell
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
T
Threat Research - Cisco Blogs
U
Unit 42
V
V2EX
V2EX - 技术
V2EX - 技术
L
LINUX DO - 最新话题
aimingoo的专栏
aimingoo的专栏
Microsoft Security Blog
Microsoft Security Blog
Recorded Future
Recorded Future
P
Privacy & Cybersecurity Law Blog
美团技术团队
小众软件
小众软件
F
Fortinet All Blogs

博客园 - greater

Matlab 7.0不断重启问题解决方法 安装Matlab过程中遇到拒绝访问怎么办? NUnit图解(一) [翻译]Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition 第二十四章 LINQ API编程(三) [翻译]Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition 第二十四章 LINQ API编程(二) [翻译]Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition 第二十四章 LINQ API编程(一) 迷人舞步 难译的英文单词 Linq 之Expression Tree再思考 VS2008代码段快捷方式小记 Linq To SQL分页失败后引发的思考 函数式编程的浅议 Linq操作符之筛选特定位置的元素 Linq与斐波那契数列共舞 Linq的那些事——从Linq扩展方法回顾C#语言基础 Linq To Object实例之过滤字符集 Linq之C#3.0语言扩展 Linq to DataSet 之Access查询 从101 LINQ Samples开始
Linq之查询非泛型集合
greater · 2008-06-19 · via 博客园 - greater

Linq to object 中我们经常可以很方便的查询多种集合比如List<T>泛型,主要的原因是他们都实现了System.Collections.Generic.IEnumerable<T>接口从而可以完成相关的查询操作但并非所有的类都实现了以上接口比如说System.Collections.ArrayList,那么通过以下三种方式可以解决。

一、OfType操作符
先看它的签名public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source)根据指定类型筛选IEnumerable的元素,当source为null返回ArgumentNullException

var q = cars.OfType<Car>().Where(c=>c.Doors==2);

二、Cast强制转换
从Cast的签名就知道它可以返回IEnumerable<T> ,
public static IEnumerable<T> Cast<T>(this IEnumerable source)
但是也要注意,如果被转换的类型中不能被转为T的则会报Invalid-
CastException异常,如果是null的话则为NullReferenceException上面代码改写为:

var q = from c in cars.Cast<Car>
        
where c.Doors==2
        select 
new {c.Name}

三、明确的类型定义
定义from中的查询类型,如


var q 
= from Car c in cars
        
where c.Doors==2
        select 
new {c.Name}