2013-12-16 28 views
1

這是什麼PHP腳本相當於C#語法拿到鑰匙?方法從陣列

<?php 
$arr = array("linux", "windows", "linux", "linux", "windows", "mac os", "unix", "mac os"); 
$unique = array_unique($arr); 
foreach($unique as $key=>$value){ 
    echo $key."\n"; 
} 
?> 

以上代碼的結果是:

0 
1 
5 
6 

因此,數組的副本都刪除,然後顯示數組的鍵。我只能顯示數組的值:

string[] arr = { "linux", "windows", "linux", "linux", "windows", "mac os", "unix", "mac os" }; 
string[] uniq = arr.Distinct().ToArray(); 
foreach (string unik in uniq) 
{ 
    textBox1.AppendText(unik+"\r\n"); 
} 

回答

5

你可以做到這一點的LINQ很容易:

var indices = arr.Distinct() 
       .Select(s => Array.IndexOf(arr,s)); 

foreach (int i in indices) 
{ 
    textBox1.AppendText(i+"\r\n"); 
} 

,或者包括值指數:

var indices = arr.Distinct() 
       .Select(s => new {s, i = Array.IndexOf(arr,s)}); 

foreach (var si in indices) 
{ 
    textBox1.AppendText(string.Format({0}: {1}\n", si.i, si.s)); 
} 

如果性能是一個問題,更高效(雖然更難理解)版本將是:

var indices = arr.Select((s, i) => new {s, i}) // select the value and the index 
       .GroupBy(si => si.s)   // group by the value 
       .Select(g => g.First());  // get the first value and index 

foreach (var si in indices) 
{ 
    textBox1.AppendText(string.Format({0}: {1}\n", si.i, si.s)); 
} 
+0

會不會'鮮明( )會導致索引從原始數組中移出? – PinnyM

+0

這將搜索數組中的每個索引。在O(n)中可以做到這一點是O(n^2)。 – Zong

+0

@PinnyM否 - 'Distinct'不會以任何方式影響原始數組。 –

1

它爲我的作品:

 string[] arr = { "linux", "windows", "linux", "linux", "windows", "mac os", "unix", "mac os" }; 
     string[] uniq = new string[0]; 
     string[] keys = new string[0]; 


     for (int i = 0; i < arr.Length; i++) 
     { 
      if (uniq.Contains(arr[i])) 
      { 
       continue; 
      } 
      else 
      { 
       uniq = uniq.Concat(new string[] { arr[i] }).ToArray(); 
       keys = keys.Concat(new string[] { i + "" }).ToArray(); 
      } 
     } 

     foreach (string key in keys) 
     { 
      textBox1.Append(key + "\r\n"); 
     } 
+0

而不是你想要一個字典的數組。然後'Contains'和添加鍵/值都是O(1)而不是O(n)。無論如何,你可能不希望追加到一個數組上,只是使用一個列表(或者在這個例子中是另一個集合)來開始。 – Zong

+0

它也在'List'集合中工作。我只是想盡可能地簡單。 –

+0

它可以工作,但隨着列表以指數速度變得越來越大,它會變得越來越慢。 –

0

這裏LINQ的解決方案 - 資源包含了 「ARR」 字符串數組中第一次出現的索引:

string[] arr = { "linux", "windows", "linux", "linux", "windows", "mac os", "unix", "mac os" }; 

var res = arr.Select((value, index) => new { value, index }) 
      .ToDictionary(pair => pair.index, pair => pair.value) 
      .GroupBy(x => x.Value) 
      .Select(x => x.First().Key); 

foreach (int i in res) 
{ 
    textBox1.AppendText(i+"\r\n"); 
}