为什么 .Equals 在此 LINQ 示例中不起作用?
为什么这会产生一个空集?
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();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
LINQ 的问题是你必须停止用 SQL 术语来思考。在 SQL 中,我们是这样思考的:-
这就是你的代码的样子。然而在 LINQ 中我们需要这样思考:-
The thing with LINQ is you've got to stop thinking in SQL terms. In SQL we think like this:-
That is what your code looks like. However in LINQ we need to think like this :-
这不起作用,因为 Select 语句会将集合中的每个值转换为该值的基础类型的名称。生成的集合将仅包含字符串值,因此它们不会具有 Int32 名称。
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.
当您进行选择时,您将获得一个
IEnumerable
。然后,您将获取列表中每个字符串的类型(全部为“String”),并过滤掉它们不等于“Int32”(整个列表)的地方。因此...列表是空的。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.等于工作得很好,这是你的查询不正确。如果要选择列表中的整数,请使用:
Equals works just fine, it's your query that isn't correct. If you want to select the integers in the list use:
反转操作的顺序:(
请注意,这也使用直接类型检查,而不是相当奇特的
.GetType().Name.Equals(…)
)。Reverse the order of the operations:
(Notice this also uses a direct type check instead of the rather peculiar
.GetType().Name.Equals(…)
).