score:12
what is the difference between
((ienumerable)source).oftype<t>()
andsource as ienumerable<t>
for me they look similar, but they are not!
you are right. they are very different.
the former means "take the source sequence and produce a brand new, different sequence composed of all the elements of the given type from the previous sequence".
the latter means "if the runtime type of the source sequence is of the given type then give me a reference to that sequence, otherwise give me null".
let me illustrate with an example. suppose you have:
ienumerable<animal> animals = new animal[] { giraffe, tiger };
ienumerable<tiger> tigers = animals.oftype<tiger>();
that will give you back a new, different sequence that contains a single tiger.
ienumerable<mammal> mammals = animals as ienumerable<mammal>;
that will give you null. animals is not a sequence of mammals, even though it is a sequence of animals that happen to only be mammals. the actual runtime type of animals is "array of animal" and an array of animals is not type-compatible with a sequence of mammals. why not? well, suppose the conversion worked, and you then said:
animals[0] = snake;
mammal mammal = mammals.first();
and hey, you just put a snake into a variable that can only contain a mammal! we cannot allow that, so the conversion does not work.
in c# 4 you can go the other way. you can do this:
ienumerable<object> objects = animals as ienumerable<object>;
because an array of animals can be treated as a sequence of objects. you put a snake in there, and a snake is still an object. this only works in c# 4 though. (and it only works if the two types are both reference types. you cannot turn an array of int into a sequence of object.)
but the key thing to understand is that the oftype<t>
method returns a brand-new sequence, and the "as" operator does a runtime type test. those are completely different things.
here's another way to look at it.
tigers = animals.oftype<tiger>()
is basically the same as
tigers = animals.where(x=>x is tiger).select(x=>(tiger)x);
that is, produce a new sequence by doing a test of each member of animals to see if it is a tiger. if it is, cast it. if it is not, discard it.
mammals = animals as ienumerable<mammal>
on the other hand, is basically the same as
if (animals is ienumerable<mammal>)
mammals = (ienumerable<mammal>) animals;
else
mammals = null;
make sense?
score:3
oftype<t>()
will only return the types inside the enumeration that are of type t. so if you have this
object[] myobjects = new object[] { 1, 2, "hi", "there" };
then call
var mystrings = myobjects.oftype<string>();
then mystrings will be an enumerable that will skip 1 and 2 and only return you "hi" and "there". you can't cast myobjects to ienumerable<string>
, because that's not what it is.
the other operator that is similar here is cast<t>()
, which will attempt to cast all of the items to type t.
var mystrings = myobjects.cast<string>();
once you start iterating over mystrings in this case, you will get a invalidcastexception
, because it will try to cast 1 to a string and fail.
Source: stackoverflow.com
Related Query
- What is the difference between ((IEnumerable)source).OfType<T>() and source as IEnumerable<T>
- What is the difference between IQueryable<T> and IEnumerable<T>?
- What is the difference between LINQ ToDictionary and ToLookup
- Linq: What is the difference between Select and Where
- What is the difference between "LINQ to Entities", "LINQ to SQL" and "LINQ to Dataset"
- Linq: What is the difference between == and equals in a join?
- What is the difference between Contains and Any in LINQ?
- What is the difference between System.Linq and System.Data.Linq?
- When using LINQ, what is the difference between && and multiple where clauses?
- What is the difference between LINQ query expressions and extension methods
- What is the difference between Linq, DLinq and XLinq?
- What are the difference between EntityFunctions.TruncateTime and DbFunctions.TruncateTime methods?
- What is the difference between where and join?
- What is the difference between Joining two different DB Context using ToList() and .AsQueryable()?
- What is the difference between Converting and Unboxing?
- What is the difference between using Join in Linq and "Olde Style" pre ANSI join syntax?
- What are the difference between .Select, .Any, and .Count when using LINQ
- In c#, what is the difference between equality members and an equality comparer, and which should you use?
- What is the difference between Equals and = in LINQ?
- what is the difference between LINQ and ADO.net
- C# LINQ: What is the difference between a Pull model and a Push model?
- What is the difference between using the Dump() extension method and using the Console.WriteLine() in the LINQPad?
- What is the difference between a regular foreach and ForEach LINQ operator when it comes to async/await
- What is the difference between First and FirstOrDefault , Last and LastOrDefault
- What is the difference between firstOrDefault() and select () when selecting single row
- In LINQ, what is the difference between Join and selecting the first item from a nested query
- What is the difference between Linq and EF syntax?
- What is the difference between Queryable.OrderBy and Enumerable.OrderBy?
- What is the difference between Object and Context in Linq/Entity Framework
- What is the difference between creating a new object inside select LINQ clause and inside a method
More Query from same tag
- Convert Linq query in repository to SelectListItem of ViewModel type
- How to get a List<TypeOf> objects, from this XML?
- System.Linq.Enumerable.Join - result is larger than input set
- How to calculate multiple averages in one query in linq to entities
- Constructing dynamic linq queries based on user input
- Storing a Dictionary<int,string> or KeyValuePair in a database
- LINQ (method) returning multiple records
- C# Instantiate Generic List with Reflected Type Information
- How to inject OR condition in Entity Framework linq query?
- linq for two tables on dotvvm framework
- xelement get same children nodes
- Entity Framework LINQ calling switchoffset() function
- Grouping, dynamic key formation, pivitoing information in C# & generating json output
- Calculate averages of multiple IEnumerable with same item count
- Appending dynamic where statements in LINQ to Entities but as an OR operator instead of AND
- Optimize the very slow following code in C#
- How to select first row of each id linq
- List with a custom type
- How this linq execute?
- How to check Entity's created date is 20 days old or not?
- ASP.NET LINQ Is it possible to do a standard SQL Query?
- Unable to project the anonymous type to model type. (The entity or complex type cannot be constructed in a LINQ to Entities query.)
- how can i return model property from lambda expression (like mvc's "html.textboxfor(yyy)")?
- Multiple textbox insert into to sql table in separate rows using LINQ
- Disable auto-generation of [Serializable] attribute by VS2015 C# compiler
- c# filter a list of double[] values
- Entity Framework Exclude Fields Query Count and POCO best way
- How to combine to generic lists with add range and select criteria?
- LINQ operations on IDictionary
- Dictionary linq select previous