2009-10-06 57 views
0

给出:如何创建包含符合条件的索引的数组?

var args = new string[] { "-one", "two", "three", "-four" }; 

会有什么神奇的功能需要的样子,为了使下面的传球?

var result = MagicFunction(args); 
Assert.AreEqual(0, result[0]); 
Assert.AreEqual(3, result[1]); 
Assert.AreEqual(2, result.Length); 

回答

2
int[] MagicFunction(string[] args) 
{ 
    return args.Select((s, i) => new { Value = s, Index = i }) // Associate an index to each item 
       .Where(o => o.Value.StartsWith("-"))   // Filter the values 
       .Select(o => o.Index)       // Select the index 
       .ToArray();          // Convert to array 
} 
+0

感谢,第一选择是干扰我。 – 2009-10-06 19:23:49

相关问题