RieqyNS13
RieqyNS13

Reputation: 495

Method to get keys from array

What is the equivalent C# syntax of this PHP script ?:

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

the result of above code is:

0
1
5
6

so, the duplicates of the array are removed and then the keys of the array are displayed. I could only display the values of array:

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

Upvotes: 1

Views: 254

Answers (3)

user3041160
user3041160

Reputation: 684

Here a LinQ solution - res contains the index of the first occurence in the "arr" string 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");
}

Upvotes: 0

Seyed Morteza Mousavi
Seyed Morteza Mousavi

Reputation: 6963

It works for me:

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

Upvotes: 1

D Stanley
D Stanley

Reputation: 152566

You can do that with Linq fairly easily:

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

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

or to include the value and the index:

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

If performance is a concern a more efficient (though harder to understand) version would be:

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

Upvotes: 5

Related Questions