[英]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. 当我在末尾添加.FirstOrDefault()时。 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'
84'T'
You are calling .FirstOrDefault()
on FirstName
which is a string
. 您正在对
FirstName
调用.FirstOrDefault()
,它是一个string
。 This will cause the .FirstOrDefault()
to be called on the IEnumberable<char>
implementation. 这将导致在
IEnumberable<char>
实现上调用.FirstOrDefault()
。 This will result in returning the first or default character in that string
. 这将导致返回该
string
的第一个字符或默认字符。
The numeric value 84
is displaying the ASCII value for T
. 数值
84
显示T
的ASCII值。 http://www.rapidtables.com/code/text/ascii-table.html http://www.rapidtables.com/code/text/ascii-table.html
Strings are arrays of characters, which can be enumerated by Linq. 字符串是字符数组,Linq可以枚举。
FirstOrDefault returns the first item in the list, or null. FirstOrDefault返回列表中的第一项,或者为null。
In this case, the first character in the array ['T', 'i', 'm'] is 'T'. 在这种情况下,数组['T','i','m']中的第一个字符为'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. 注意:使用FirstOrDefault可以返回null,如果没有匹配项,则将导致NullReferenceException。
Alternatively: 或者:
var match = people.FirstOrDefault(n => n.FirstName == FirstName && n.LastName == LastName);
return (match == null) ? "" : match.FirstName;
是的- string
本质上是IEnumerable<char>
因此,当您调用FirstOrDefault()
,您将返回IEnumerable
的第一个char
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.