Akhil RJ
Akhil RJ

Reputation: 357

Take latest value from complex collection

i'm getting data from MongoDb in sorted order with key[not unique] as AB ,so i have to club the response and take the top unique values based on key using Linq[c#]

Response :

[{
        "AB": "XY",
        "BC": "TRAVEL",
        "CD": "75",
        "EF": "21"
    },
    {
        "AB": "TY",
        "BC": "STOP",
        "CD": "344",
        "EF": "55"
    },
    {
        "AB": "XY",
        "BC": "STOP",
        "CD": "45",
        "EF": "44"
    },
    {
        "AB": "ZZ",
        "BC": "STOP",
        "CD": "89",
        "EF": "33"
    },
    {
        "AB": "TY",
        "BC": "STOP",
        "CD": "67",
        "EF": "88"
    },
    {
        "AB": "ZZ",
        "BC": "TRAVEL",
        "CD": "14",
        "EF": "55"
    }
]

Response is in sorted format i.e first response is latest

The result that i want to produce is :

[{
    "AB": "XY",
    "BC": "TRAVEL",
    "CD": "75",
    "EF": "21"
},
{
    "AB": "ZZ",
    "BC": "STOP",
    "CD": "89",
    "EF": "33"
},
{
    "AB": "TY",
    "BC": "STOP",
    "CD": "344",
    "EF": "55"
}]

as the AB key can contain different values

Upvotes: 2

Views: 49

Answers (1)

Fabjan
Fabjan

Reputation: 13676

Well, you could utilize LINQ GroupBy method:

var filteredResponse = response.GroupBy(o => o.AB).Select(g => g.First()).ToList();

Upvotes: 3

Related Questions