genespos genespos - 10 months ago 54 Question

Predicate to use Find on a List of Tuple

I have this


Public TblDic As New Dictionary(Of String, List(Of Tuple(Of Date, Date, Decimal)))

I need to retrieve the 3rd item (Decimal) of the Tuple having the highest date on 2nd item.

I was able to retrieve the 3rd item by knowing the date but I wasn't able to retrieve the highest date:

Dim LastDate As Date = Date.ParseExact("31/12/2016", "dd/MM/yyyy",
New CultureInfo("it-IT"), DateTimeStyles.None)
Dim LastRate2 As Decimal = TblDic("Legali").Find(Function(D) D.Item2 = LastDate).Item3

Another way could be to put all tuple into a DataTable and use DataTable.Select to retrieve the decimal field this way:

Dim LastRate As Decimal = DT_Rates.Select("EndDate=MAX(EndDate)")(0).Field(Of Decimal)("Rate")

So, my questions are:

1) is it possible to use List.Find without knowing the last date?

2) what is the best practice between List.Find and DataTable.Select?

Answer Source

You could use Find... maybe? But I think this is simple enough without it.

Dim LastRate As Decimal = TblDic.
    SelectMany(Function(k) k.Value).
    OrderByDescending(Function(k) k.Item2).

SelectMany() takes many sequences and flattens them into one sequence. The sequences in this case are values of the dictionary, List(Of Tuple(Of Date, Date, Decimal))

OrderByDescending() orders the flattened sequence by the predicate, which returns the Date of the Tuple(Of Date, Date, Decimal). This orders all the Tuple(Of Date, Date, Decimal) across all the lists since they were flattened

First() takes the first Tuple(Of Date, Date, Decimal) after it was ordered by the date descending

Item3 returns the Decimal of the Tuple(Of Date, Date, Decimal)