Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

.net - Does LINQ work with IEnumerable?

I have a class that implements IEnumerable, but doesn't implement IEnumerable<T>. I can't change this class, and I can't use another class instead of it. As I've understood from MSDN LINQ can be used if class implements IEnumerable<T>. I've tried using instance.ToQueryable(), but it still doesn't enable LINQ methods. I know for sure that this class can contain instances of only one type, so the class could implement IEnumerable<T>, but it just doesn't. So what can I do to query this class using LINQ expressions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use Cast<T>() or OfType<T> to get a generic version of an IEnumerable that fully supports LINQ.

Eg.

IEnumerable objects = ...;
IEnumerable<string> strings = objects.Cast<string>();

Or if you don't know what type it contains you can always do:

IEnumerable<object> e = objects.Cast<object>();

If your non-generic IEnumerable contains objects of various types and you are only interested in eg. the strings you can do:

IEnumerable<string> strings = objects.OfType<string>();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...