这个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";
}
?>
Run Code Online (Sandbox Code Playgroud)
上面代码的结果是:
0
1
5
6
Run Code Online (Sandbox Code Playgroud)
因此,删除数组的副本,然后显示数组的键.我只能显示数组的值:
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");
}
Run Code Online (Sandbox Code Playgroud)
你可以很容易地使用Linq做到这一点:
var indices = arr.Distinct()
.Select(s => Array.IndexOf(arr,s));
foreach (int i in indices)
{
textBox1.AppendText(i+"\r\n");
}
Run Code Online (Sandbox Code Playgroud)
或包括值和索引:
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));
}
Run Code Online (Sandbox Code Playgroud)
如果性能是一个问题,那么更高效(虽然难以理解)的版本将是:
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));
}
Run Code Online (Sandbox Code Playgroud)