Reputation: 43
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);
}
}
}
Upvotes: 0
Views: 147
Reputation: 7803
This will return a collection of tmdbMovie
classes that have the department equal to "Directing".
var directingCollection = directorsData.crew.Where(x => x.Department.Equals("Directing"));
If you want only the names, in a string collection, you can do the following:
var nameCollection = directorsData.crew.Where(x => x.Department.Equals("Directing"))
.Select(x => x.Name).ToList();
If you would like to loop through all the names, you can do the following:
nameCollection.ForEach(x =>
{
//X will be the string value of the name
//Your code here
});
Upvotes: 0
Reputation: 7352
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);
Upvotes: 3