hbc hbc - 4 months ago 10
ASP.NET (C#) Question

How to iterate in a list to find names and values with linq

I'm developing an MVC project with .net. I have a json like this and its very long

{
credit_id: "57214f73c3a3681e800005f4",
department: "Production",
id: 84493,
job: "Casting",
name: "Mickie McGowan",
profile_path: "/k7TjJBfINsg8vLQxJwos6XObAD6.jpg"
},
{
credit_id: "572294979251413eac0007e2",
department: "Art",
id: 7927,
job: "Art Direction",
name: "Ricky Nierva",
profile_path: null
},
{
credit_id: "572297cdc3a3682d240008f9",
department: "Visual Effects",
id: 7894,
job: "Visual Effects",
name: "Jean-Claude Kalache",
profile_path: null
},


I put that jason in a list called "directorsData.crew" I have to find the names which their departments are "Directing" and add them in a directors list. How can I do it with LINQ?

like this

var directorsData = (tmdbMovie)JsonConvert.DeserializeObject<tmdbMovie>(findDirectors);

List<string> directors = new List<string>();
if (directorsData != null)
{
if (directorsData.crew.Count != 0)
{
foreach (var item in directorsData.crew)
{
var name = directorsData.crew. ===?
directors.Add(name);
}
}
}

Answer

Using Linq you can get all names as list which department is Directing

var nameList = directorsData.crew.Where(a =>a.department == "Directing")
                                 .Select(a => a.name).ToList();

also, you can remove type casting in deserialization

var directorsData = JsonConvert.DeserializeObject<tmdbMovie>(findDirectors);
Comments