C# Table query using GoupBy based on maximum version value in Linq Method

58 views Asked by At

I have a table called "TB_USER_ROUTE" in which when I want to consult the information it shows the following result.

+------------+----------------------+--------------------+------------+-----------------+---------+
| ID         | FK_CODE_TYPE         | A_SEQ              | A_IDNAME   | A_NAMEFULL      | A_VERSION|
+------------+----------------------+--------------------+------------+-----------------+---------+
| 1          | 1                    | 1                  |       A2   | 077-25000000    | 1       |
| 2          | 1                    | 2                  |       A3   | 075-12458969    | 1       |
| 3          | 2                    | 1                  |       A2   | 077-25000000    | 1       |
| 4          | 4                    | 1                  |       A2   | 077-25000000    | 1       |
| 5          | 4                    | 2                  |       A3   | 075-12458969    | 1       |
| 6          | 1                    | 1                  |       A2   | 077-25000000    | 2       |
| 7          | 1                    | 2                  |       A3   | 075-12458969    | 2       |

But I want to know how to write a statement through LINQ Method C# to obtain the following result.

+------------+----------------------+--------------------+------------+-----------------+---------+
| ID         | FK_CODE_TYPE         | A_SEQ              | A_IDNAME   | A_NAMEFULL      | A_VERSION|
+------------+----------------------+--------------------+------------+-----------------+---------+
| 6          | 1                    | 1                  |       A2   | 077-25000000    | 2       |
| 7          | 1                    | 2                  |       A3   | 075-12458969    | 2       |
| 3          | 2                    | 1                  |       A2   | 077-25000000    | 1       |
| 4          | 4                    | 1                  |       A2   | 077-25000000    | 1       |
| 5          | 4                    | 2                  |       A3   | 075-12458969    | 1       |

What I am looking for is to create a statement that when called shows me in order all the FK_CODE_TYPE based on the maximum version existing in A_VERSION That is, in the example I have 4 records with FK_CODE_TYPE = 1 but 2 are version "1" and the other 2 are version "2" so it should only show me those of the recent version which in this case is "2" and so on with any FK_CODE_TYPE that has the higher version.

I use this code but only works to get the first result

var result = tblist.GroupBy(x => x.FK_CODE_TYPE, (key,g) => g.OrderBy(e => e.A_SEQ).First());

What should I do to get the results I'm looking for without using first()?

0

There are 0 answers