tags:

views:

249

answers:

6

Why does this yield 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();
+10  A: 

When you do your select you're getting an IEnumerable<String>. Then you're taking the types of each string in the list (which is all "String") and filtering them out where they aren't equal to "Int32" (which is the entire list). Ergo...the list is empty.

Jason Punyon
+1  A: 
var newTypes = types.Select(x => x.GetType().Name)
    .Where(x => x.Equals("Int32"))
    .OrderBy(x => x);
Darin Dimitrov
+1  A: 

This doesn't work because the Select statement will convert every value in the collection to the name of the underlying type of that value. The resulting collection will contain only string values and hence they won't ever have the name Int32.

JaredPar
+4  A: 

Equals works just fine, it's your query that isn't correct. If you want to select the integers in the list use:

var newTypes = types.Where( x => x.GetType().Name.Equals("Int32") )
                    .OrderBy( x => x );
tvanfosson
+3  A: 

Reverse the order of the operations:

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

(Notice this also uses a direct type check instead of the rather peculiar .GetType().Name.Equals(…)).

Konrad Rudolph
+2  A: 

The thing with LINQ is you've got to stop thinking in SQL terms. In SQL we think like this:-

SELECT Stuff
FROM StufF
WHERE Stuff
ORDER BY Stuff

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

FROM Stuff
WHERE Stuff
SELECT Stuff
ORDER BY Stuff
AnthonyWJones
yes, you must remember to like yoda think
Edward Tanguay