Home > Software design >  Linq. Filter objects from nested list inside of an object
Linq. Filter objects from nested list inside of an object

Time:01-03

I have list of objects that looks like this:

teams: [
  {
    "teamName": "Bayern",
    "players":[
      {
        "name": "Neuer",
        "status": "available"
      },
      {
        "name": "Muller",
        "status": "unavailable"
      },
      {
        "name": "Pavard",
        "status": "unknown"
      }
    ]
  },
  {
    "teamName": "Borrusia",
    "players":[
    {
        "name": "Haller",
        "status": "available"
      },
    {
        "name": "Modeste",
        "status": "unavailable"
      }
    ]
  }
]

So in short i have list of teams where you can find teamName attribute and list of players in that team. Every player has status property which is Enum. Is it possible to filter the nested list players so i am left with only the players that have status available?

I want to get at the end object like this:

teams: [
  {
    "teamName": "Bayern",
    "players":[
      {
        "name": "Neuer",
        "status": "available"
      }
    ]
  },
  {
    "teamName": "Borrusia",
    "players":[
    {
        "name": "Haller",
        "status": "available"
      }
    ]
  }
]

CodePudding user response:

Try with this code, just use a method 'Where' and you will get only players availables:

var result = teams.Select(team => new 
{ 
  teamName = team.teamName,
  players = team.players.Where(player => player.status == "available")
});
  • Related