Shiv
Shiv

Reputation: 149

FirstOrDefault() returns first letter of the string

I've a people object

        people.Add(new Person { FirstName = "Tim", Id = 1, LastName = "Corey" });
        people.Add(new Person { FirstName = "Sue", Id = 2, LastName = "Storm" });
        people.Add(new Person { FirstName = "Bilbo", Id = 3, LastName = "Baggins" });

I'm trying to query it by passing FirstName and LastName (Tim, Corey)

return people.Where(names => names.FirstName == FirstName && names.LastName == LastName).FirstOrDefault().FirstName;

This returns output as

"Tim"

When I added .FirstOrDefault() at the end. It brought strange output as

return people.Where(names => names.FirstName == FirstName && names.LastName == LastName).FirstOrDefault().FirstName.FirstOrDefault();

84 'T'

Could anyone explain how did the output produced.

84 'T'

Upvotes: 0

Views: 4794

Answers (3)

Matt Rowland
Matt Rowland

Reputation: 4595

You are calling .FirstOrDefault() on FirstName which is a string. This will cause the .FirstOrDefault() to be called on the IEnumerable<char> implementation. This will result in returning the first or default character in that string.

The numeric value 84 is displaying the ASCII value for T. http://www.rapidtables.com/code/text/ascii-table.html

Upvotes: 6

MetalMichael
MetalMichael

Reputation: 129

Strings are arrays of characters, which can be enumerated by Linq.

FirstOrDefault returns the first item in the list, or null.
In this case, the first character in the array ['T', 'i', 'm'] is 'T'.

I think this is what you meant to write:

return people.First(names => names.FirstName == FirstName && names.LastName == LastName).FirstName;

Note: Using FirstOrDefault can return null, which would cause a NullReferenceException if there are no matches.

Alternatively:

var match = people.FirstOrDefault(n => n.FirstName == FirstName && n.LastName == LastName);
return (match == null) ? "" : match.FirstName;

Upvotes: 2

Michael
Michael

Reputation: 1596

Yes - a string is essentially a IEnumerable<char> so when you call FirstOrDefault(), you're returning the first char in the IEnumerable.

Upvotes: 0

Related Questions