NSDictionary - 获取唯一记录选择哪些键必须是唯一的

NSDictionary - Get unique records choosing which keys has to be uniques

我有一组带有 N 个键的字典。我想创建一个只包含一些键的唯一字典数组。

例子。我的字典:

{
    "m_anno" = 2017;
    "m_c_ultimo" = "4.130";
    "m_cod" = 4522;
    "m_cod_art" = "*B";
    "m_des" = "SCRITTA BIANCA NISSAN";
    "m_ditta" = SIS;
    "m_prz" = "0.000";
    "m_qta" = "1.000";
    "m_sconto" = {
    };
},
{
    "m_anno" = 2017;
    "m_c_ultimo" = "25.020";
    "m_cod" = 4522;
    "m_cod_art" = "000/01200";
    "m_des" = "CABLAGGIO X TIMONE";
    "m_ditta" = SIS;
    "m_prz" = "0.000";
    "m_qta" = "1.000";
    "m_sconto" = {
    };
},
{
    "m_anno" = 2017;
    "m_c_ultimo" = "1.000";
    "m_cod" = 4523;
    "m_cod_art" = 000000;
    "m_des" = "BLISTER O-RING 3106";
    "m_ditta" = SIS;
    "m_prz" = "0.000";
    "m_qta" = "1.000";
    "m_sconto" = {
    };
},

我想获得 m_anno 和 m_cod 键的唯一值。预期结果:

{
  {
     "m_anno" = 2017
     "m_cod" = 4522
  }
  {
      "m_anno" = 2017
      "m_cod" = 4523
  }
}

哪种方法最简单?

基本上你必须遍历数组(quelle surprise!)并将其放入集合中,如果该对尚不存在。第二个任务可以通过使用 NSSetNSOrderedSet 的实例来完成,具体取决于必须保留顺序的要求:

NSArray *values = …; // You start with this
NSMutableOrderedSet *uniquePairs = [NSMutableOrderedSet new];
for( NSDictionary *value in values )
{
   NSDictionary *pair = @{ @"m_anno":[value objectForKey:@"m_anno"], @"m_cod":[value objectForKey:@"m_cod"] }; // Create smaller version
   [uniquePairs addObject:pair];
}

可能有更优雅的方式。 (取决于观点)

添加字典,将数组缩减为所需的键:

NSDictionary( UnifyAnnoAndCodeAddition )
- (NSDictionary*)annoAndCod
{
  return @{ @"m_anno":[self objectForkey:@"m_anno"], @"m_cod":[self objectForKey:@"m_code"]};
}

然后使用key-value编码创建一个缩减字典数组,做一个这样的集合:

NSArray *values = …; // You start with this
NSArray *pairs = [values valueForKey:@"annoAndCod"]; 
NSOrderedSet = [NSOrderedSet orderedSetWithArray:pairs];

好吧,至少它更短了。