简体   繁体   English

使用LINQ从对象列表中获取一组特定的对象

[英]using LINQ to get a particular set of objects from a list of objects

I have a code that returns a set of objects. 我有一个返回一组对象的代码。 I want to segregate a particular object from that set. 我想从该集合中分离出一个特定的对象。 I'm trying to use LINQ to do that. 我正在尝试使用LINQ来做到这一点。 But I'm not getting that, 但是我不明白

var registerAck = ((pointAck)((response.Item))).Items[0].Item;

var poke = ((pointAck)((response.Item))).Items.Where(x => x.GetType() == typeof(poker));

I'm getting a System.Linq.Enumerable.WhereArrayIterator<> in my poke. 我戳到了System.Linq.Enumerable.WhereArrayIterator <>。

What am I doing wrong here? 我在这里做错了什么?

Add .ToList() to convert it to the type of System.Collections.Generic.List<TSource> 添加.ToList()将其转换为System.Collections.Generic.List<TSource>的类型

var poke = ((pointAck)((response.Item))).Items
           .Where(x => x.GetType() == typeof(poker)).ToList();
  1. Adding .ToList may or may not be required, because it depends on how you want to use poke . 可能需要也可能不需要添加.ToList ,因为这取决于您要使用poke For example, if you are going to iterate over the results using foreach only once, then .ToList is redundant, and unnecessary code execution and allocations. 例如,如果只使用一次foreach遍历结果,则.ToList是多余的,并且不必要的代码执行和分配。

In short, there may be nothing wrong with your code, depending on how you want to further use poke . 简而言之,代码可能没有什么问题 ,具体取决于您希望进一步使用poke

  1. While we are at it, FYI, there is an alternative to specific filtering you are doing here with Where method.. Checkout .OfType 仅供参考,您可以使用Where方法在此处进行特定过滤的替代方法.OfType

http://msdn.microsoft.com/en-us/library/vstudio/bb360913(v=vs.100).aspx http://msdn.microsoft.com/en-us/library/vstudio/bb360913(v=vs.100).aspx

It will be slightly more compact and more readable. 它将更加紧凑和可读。 Items.OfType<poker>();

Sorry. 抱歉。 I forgot to add .ToList(). 我忘了添加.ToList()。 It works. 有用。

var poke = ((pointAck)((response.Item))).Items.Where(x => x.GetType() == typeof(poker)).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM