175-linq-example-mapping-one-array-to-another-in-c

Reading Time: 1 minute

If we have an array of strings, with people names for example and would like to display them in some arbitrary order given in another array of integers, we can manipulate two arrays with LINQ in C#. Here is LINQ example of mapping one array to another in C#

int[] numbers = { 5, 4, 3, 6, 2, 0 };
string[] people = { “John”, “Ned”, “Tom”, “Ann”, “Patrick”, “Carla”, “Lynda”};

var numbersPeople =

from n in numbers
select people[n];

string str_write;
str_write = “People on random display:” + System.Environment.NewLine;

foreach (var s in numbersPeople)
{

str_write += s.ToString() + System.Environment.NewLine;

}
textBox1.Text = str_write;

Introducing an variant type with LINQ query we can have our strings sorted in order defined in our integer array that we mapped on the string array.

External links:

LINQ example of manipulating two array in C# on Igoro
LINQ example of manipulating two array in C# on Stackoverflow
LINQ example of manipulating two array in C# on Beansoftware

Leave a Reply

Your email address will not be published. Required fields are marked *

*