2016-01-22 84 views
1

我來自C#,LINQ就像第二個本質。我有以下功能,我不知道是否可以縮短我「跳過」特殊屬性的部分?我有屬性「名稱」的數組,我想從self.attributes不包含這些名稱返回屬性列表。這是我的功能,這將是1號線在C#:(在NSMutableArray中查找項目

- (NSArray*)getDisplayedAttributes 
{ 
    //Get stop attributes 
    NSMutableArray *attributes = [[NSMutableArray alloc] init]; 
    for (Attribute *attr in self.attributes) 
    { 
     // Skip special attribute 
     BOOL found = false; 
     for (Attribute *sa in @[@"D:AR",@"D:AS",@"D:ARF",@"D:DD",@"D:DH"]) 
     { 
      if ([(NSString*)sa isEqualToString:attr.name]) 
      { 
       found = true; 
       break; 
      } 
     } 

     if (found) continue; 

     Attribute *attribute = [[Attribute alloc] init]; 
     attribute.name = attr.name; 
     attribute.value = attr.value;   
     [attributes addObject:attribute]; 
    } 

    return attributes; 
} 
+0

你能給一個樣本輸入和期望輸出的例子嗎? – matt

回答

1

它可以是一個班輪在Objective-C也

- (NSArray*)getDisplayedAttributes 
{ 
    return [self.attributes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"NOT name IN %@",@[@"D:AR",@"D:AS",@"D:ARF",@"D:DD",@"D:DH"]]]; 
} 

雖然這是一個長行:)

請注意,此代碼返回與原始數組中相同的Attribute對象,它不會像您的代碼中那樣創建新對象。如果要過濾的數組包含原始屬性的克隆,則需要在Attribute上實施copy方法。

+0

是的,我將需要副本,但是沒關係,因爲我需要對這些新副本做更多的工作。上面的代碼正是我正在尋找的。只是學習我的方式.. – katit

+1

@Rob感謝注意到,我糾正了我的答案。我應該停止在SO編輯器中直接輸入代碼:P – Cristik

+0

順便說一句,不是實現'copy',而是建議實現'copyWithZone',而不是遵循'NSCopying'。然後,該對象不僅會自動響應'copy',而且還可以像'[[NSArray alloc] initWithArray:copy:]'一樣複製'Attribute'對象的數組。 – Rob