Haris
Haris

Reputation: 915

Access field from generic List in GetRange() method?

Does anybody know how to access a specific field from List<>? I cant figure out howto access a specific field in newList object.

  List<Liner> LX = new List<Liner>();

  public class Liner
  {
      public double Temperature { get; set; }
      public double Moisture { get; set; }
  }

newList = LX.OrderBy(x => x.Temperature).ToList();

var lstMXLast = newList.GetRange(8755, 5);  // I need only 5 specific Moisture records in this case. 

Upvotes: 1

Views: 614

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460208

GetRange returns a copy of the list with the given range. So your list needs at least 8760 items. To select only the Moisture property of your objects, you can use LINQ's Select:

var lstMoistures = newList.GetRange(8755, 5).Select(l => l.Moisture).ToList();

Note: you need the ToList at the end only if you want to persist the query. Your ToList at the end of the OrderBy query is useless because you want to chain another query. I would materialze LINQ queries only as late as possible.

You could also use LINQ for the whole thing:

var lstMoistures = newList.Skip(8755).Take(5).Select(l => l.Moisture).ToList();

Assuming that you originally wanted to select the 5 liners with the highest temperature, this should give you the correct result:

var lstMoistures = LX.OrderByDescending(x => x.Temperature).Take(5).Select(l => l.Moisture).ToList();

Upvotes: 1

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48550

Use

var results = newList.GetRange(8755, 5).Select(m => m.Moisture);

It will give you moisture levels of Liner returned by GetRange() i.e. 5 moisture levels.

Upvotes: 0

Rawling
Rawling

Reputation: 50144

You can use newList.GetRange(8755, 5).Select(l => l.Moisture) to just get the Moisture component from the five selected Liner records.

Upvotes: 0

Related Questions