2016-08-05 57 views
0

我正在用.net開發MVC項目。我有一個JSON像這樣和很長的如何在列表中迭代以查找linq的名稱和值

{ 
    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 
}, 

我把傑森在一個名爲「directorsData.crew」我一定要找到,他們的部門正在「導演」的名稱,並在董事列表中添加列表。我怎樣才能用LINQ做到這一點?

這樣

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); 
     } 
    } 
} 
+1

僅供參考,當你反序列化,你並不需要強制類型轉換回'tmdbMovie',因爲你正在使用的通用'DeserializeObject ()',它已經返回該類型:) –

回答

3

使用LINQ,你可以得到所有名稱爲列表哪個部門Directing

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

也可以去除型鑄件反序列化

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

所以我想我那麼不需要那些foreach? – hbc

+0

是的,你不需要再foreach – Mostafiz

+0

完全可以工作,謝謝 – hbc

0

這將返回一批tmdbMovie擁有該部門的班級t等於「導演」。

var directingCollection = directorsData.crew.Where(x => x.Department.Equals("Directing")); 

如果你只想要的名字,在一個字符串集合,你可以做到以下幾點:

var nameCollection = directorsData.crew.Where(x => x.Department.Equals("Directing")) 
             .Select(x => x.Name).ToList(); 

如果你想遍歷所有的名字,你可以做到以下幾點:

nameCollection.ForEach(x => 
{ 
    //X will be the string value of the name 
    //Your code here 
}); 
+0

你太棒了 – hbc

相關問題