Reputation: 71
I have a custom Object that contains an Object that has many properties.
Here is my Custom Object:-
private class ClosingBookItem
{
public IOrder Order;
public double EntryPrice;
// Maximum Adverse Effect Price
public double MAEP;
// closing order has a target of mean price
public bool MidTarget;
public ClosingBookItem(IOrder order, double entryPrice, double maep, bool midTarget)
{
Order = order;
EntryPrice = entryPrice;
MAEP = maep;
MidTarget = midTarget;
}
}
The Object Order has a property that is a Double called LimitPrice.
I have created a list of this custom object:-
List<ClosingBookItem> closingsBook = new List<ClosingBookItem>();
How can I return the index of the Item in the list that contains the minimum value for Order.LimitPrice ?
I have looked around but couldn't find a good description and have tried a few things but with no luck.
Upvotes: 2
Views: 1452
Reputation: 460138
You can use
double minLimitPrice = closingsBook.Min(b => b.Order.LimitPrice);
int index = closingsBook.FindIndex(b => b.Order.LimitPrice == minLimitPrice);
Another pure LINQ approach:
index = closingsBook.Select((b, ix) => new { Book = b, Index = ix })
.OrderBy(x => x.Book.Order.LimitPrice)
.First()
.Index;
If you want to find all indexes, no problem at all:
IEnumerable<int> allIndexes = closingsBook.Where(b => b.Order.LimitPrice == minLimitPrice);
Console.WriteLine(String.Join(",", allIndexes)); // f.e.
the pure LINQ approach which selects all indexes:
IEnumerable<int> allIndexes = closingsBook.Select((b, ix) => new { Book = b, Index = ix })
.GroupBy(x => x.Book.Order.LimitPrice) // build groups per LimitPrice
.OrderBy(g => g.Key) // order by that ascending
.First() // take the group with lowest LimitPrice
.Select(x => x.Index); // select the indexes of that group
Upvotes: 6
Reputation: 603
With Tim's answer you'll have the first item that matches the condition.
Just in case you have several items with the same price and you want to have the index of all these items, you can use this :
int minPrice = closingsBook.Min(book => book.LimitPrice);
var indexes = closingsBook.Select((book, index) => new { book, index })
.Where(x => x.book.LimitPrice== minPrice)
.Select(x => x.index);
Upvotes: 0