Why does LINQ not work .Equals in this example?

Why does this give an empty set?

Object[] types = {23, 234, "hello", "test", true, 23}; var newTypes = types.Select(x => x.GetType().Name) .Where(x => x.GetType().Name.Equals("Int32")) .OrderBy(x => x); newTypes.Dump(); 
+4
source share
6 answers

When you make your choice, you get an IEnumerable<String> . Then you take the types of each line in the list (it's all โ€œStringโ€) and filter them where they are not equal to โ€œInt32โ€ (which is a complete list). Ergo ... the list is empty.

+11
source

It works just the same; your request is incorrect. If you want to select integers in the list, use:

 var newTypes = types.Where( x => x.GetType().Name.Equals("Int32") ) .OrderBy( x => x ); 
+5
source

Cancel the order of operations:

 var newTypes = types.Where(x => x is int) .OrderBy(x => x) .Select(x => x.GetType().Name); 

(Note that this also uses direct type checking instead of the rather peculiar .GetType().Name.Equals(โ€ฆ) ).

+5
source

The thing with LINQ is that you need to stop thinking in terms of SQL. In SQL, we think like this: -

 SELECT Stuff FROM StufF WHERE Stuff ORDER BY Stuff 

Here is what your code looks like. However, in LINQ we need to think like this: -

 FROM Stuff WHERE Stuff SELECT Stuff ORDER BY Stuff 
+3
source
 var newTypes = types.Select(x => x.GetType().Name) .Where(x => x.Equals("Int32")) .OrderBy(x => x); 
+1
source

This does not work because the Select statement converts each value in the collection into the name of the base type of that value. As a result, the collection will contain only string values โ€‹โ€‹and, therefore, they will never have the name Int32.

+1
source

All Articles