Home > database >  Linq get new list from a list of object property which is a list itself
Linq get new list from a list of object property which is a list itself

Time:10-16

So I have a list like this:

{
  "images": [
    {
      "imageLink": "link1",
       "pIds": [
        "id1"
      ]
    },
    {
      "imageLink": "link2",
      "pIds": [
        "id2"
      ]
    },
    {
      "imageLink": "link3",
      "pIds": [
        "id2"
      ]
    }
  ]
}

I want to create a list which contains all the unique pIds from above list . How Do I do so? I am trying it like this

var pIds  = oldList.Select(p=>p.Ids).ToList();

but I dont want List of lists just the elements inside the pIds in oldList.

like:

pIds = ["id1","id2"]

CodePudding user response:

You are looking for SelectMany to flatten the nested enumerations:

var pIds  = oldList
  .SelectMany(p => p.Ids)
  .Distinct() // to get unique ids
  .ToList();
  • Related