简体   繁体   中英

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. 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.

What am I doing wrong here?

Add .ToList() to convert it to the type of 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 . 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.

In short, there may be nothing wrong with your code, depending on how you want to further use poke .

  1. While we are at it, FYI, there is an alternative to specific filtering you are doing here with Where method.. Checkout .OfType

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(). It works.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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