When to use Cast() and Oftype() in Linq

I am aware of two methods of casting types to IEnumerable from an Arraylist in Linq and wondering in which cases to use them?

eg

IEnumerable<string> someCollection = arrayList.OfType<string>()

or

IEnumerable<string> someCollection = arrayList.Cast<string>()

What is the difference between these two methods and where should I apply each case?


OfType - return only the elements of type x.
Cast - will try to cast all the elements into type x. if some of them are not from this type you will get InvalidCastException

EDIT
for example:

object[] objs = new object[] { "12345", 12 };
objs.Cast<string>().ToArray(); //throws InvalidCastException
objs.OfType<string>().ToArray(); //return { "12345" }

http://solutionizing.net/2009/01/18/linq-tip-enumerable-oftype/

Fundamentally, Cast() is implemented like this:

public IEnumerable<T> Cast<T>(this IEnumerable source)
{
  foreach(object o in source)
    yield return (T) o;
}

Using an explicit cast performs well, but will result in an InvalidCastException if the cast fails. A less efficient yet useful variation on this idea is OfType():

public IEnumerable<T> OfType<T>(this IEnumerable source)
{
  foreach(object o in source)
    if(o is T)
      yield return (T) o;
}

The returned enumeration will only include elements that can safely be cast to the specified type.


You should call Cast<string>() if you know that all of the items are string s.
If some of them aren't strings, you'll get an exception.

You should call OfType<string>() if you know that some of the items aren't string s and you don't want those items.
If some of them aren't strings, they won't be in the new IEnumerable<string> .

链接地址: http://www.djcxy.com/p/73724.html

上一篇: C#“为”投与经典剧组

下一篇: 何时在Linq中使用Cast()和Oftype()