Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does .Equals not work in this LINQ example?

Tags:

c#

linq

linqpad

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();
like image 284
Edward Tanguay Avatar asked Nov 27 '22 23:11

Edward Tanguay


2 Answers

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.

like image 61
Jason Punyon Avatar answered Dec 05 '22 15:12

Jason Punyon


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 );
like image 37
tvanfosson Avatar answered Dec 05 '22 15:12

tvanfosson