konrad8767
konrad8767

Reputation: 139

Linq. Filter objects from nested list inside of an object

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"
      }
    ]
  }
]

Upvotes: 0

Views: 59

Answers (1)

Raziak
Raziak

Reputation: 388

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")
});

Upvotes: 2

Related Questions