PROWAREtech

articles » current » dot-net » index-value-when-using-linq-select

.NET: Find the Index Value When Using LINQ Select()

How to know the current index value of an item when using the Language Integrated Query Select() method; example in C#.

Here is an example of making a one-hot encoding for tasks like classification/categorization in machine learning. It requires the index during the Select() modifier.


var string_array = new string[] { "D", "A", "I", "G", "F", "C", "J", "E", "H", "B" }.OrderBy(x => x).ToArray();
var array_of_arrays = string_array.Select((val, index) =>
{
    var one_hot = new double[string_array.Length];
    one_hot[index] = 1; // NOTE: index used here
    return one_hot;
}).ToArray();

foreach (var str in string_array)
    Console.Write(str + ' ');
Console.WriteLine("\r\n");

foreach (var array in array_of_arrays)
{
    foreach (var dbl in array)
        Console.Write(dbl + " ");
    Console.WriteLine();
}

The above code will output this:

A B C D E F G H I J

1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT