Kevin S. Miller
Kevin S. Miller

Reputation: 974

Linq, from list of objects, create list of properties based on another property's value

I need to get a list of risePeriods where bitPos > 2.

class Bit
{           
  public int bitPos { get; set; }        
  public int risePeriod { get; set; }
}

List<Bit> dataBits;

I tried

IEnumerable<int> rpList = dataBits
    .Where(bit => bit.bitPos > 2)
    .Select(bit => bit.risePeriod);

and

IEnumerable<int> rpList = from bit in dataBits 
                          where bit.bitPos > 2 
                          select bit.risePeriod

as well as other ways, but each returns the entire dataBits list instead of just a list of risePeriods. This should be simple - right?

Thanks!

Upvotes: 0

Views: 976

Answers (1)

Lew
Lew

Reputation: 1278

I've tried this and it seems to be working fine, as I suspected as the syntax and logic looks correct. You could try adding a call to ToList which will make it more clear when inspected that it is a list of integers. If not, there must be something else going on here. Here's the code I suggest:

IEnumerable<int> rpList = dataBits
.Where(bit => bit.bitPos > 2)
.Select(bit => bit.risePeriod)
.ToList();

Upvotes: 4

Related Questions