从数组中获取键的方法

时间:2013-12-16 18:08:15

标签: c# arrays

这个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");
}

3 个答案:

答案 0 :(得分: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));
}

答案 1 :(得分: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");
        }

答案 2 :(得分:0)

这里的LinQ解决方案 - res包含“array”字符串数组中第一次出现的索引:

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");
}