Accessing Array and Collection using LINQ


Introduction

This article will teach you about how you can Access Array elements and Collections using LINQ.

Technology 

CSharp .net 3.5

Implementation

I will teach you with one example of Array and another of List<T> collection. If you are beginner to LINQ, let me teach you basic query format for writing query for LINQ.

from element  in <Collection/Array Name> where <Condition Here> orderby  <SortElementName>  select element

LINQ queries result can be retrieve in IEnumerable<T>

So, we will retrieve result of LINQ query into IEnumerable<T> object.

First I have setup Interface of application like below one 

1.gif

Take one list box to display result of query and two buttons one for showing retrieval from array and one for List<T>

Working with List<T> using LINQ

private void button1_Click(object sender, EventArgs e)

{

   //Working with List<T> Using LINQ

 

   // Creating List

   List<string> list = new List<string>();

   list.Add("orange");

   list.Add("cherry");

   list.Add("banana");

   list.Add("strowberry");

   list.Add("mango");

   list.Add("fig");

 

   //Select Fruites whose String length is less than 3

 

   IEnumerable<string> result = from Str in list where Str.Length > 3 orderby Str.Length select Str;

 

   listBox1.Items.Clear();

   foreach (string s in result)

   {

        listBox1.Items.Add(s);

   }

}

 
Working with Array using LINQ

private void button2_Click(object sender, EventArgs e)

{

    //Creating Array

   string[] StringArray = new string[5];

 

   StringArray[0] = "abc";

   StringArray[1] = "aac";

   StringArray[2] = "abd";

   StringArray[3] = "bad";

   StringArray[4] = "test";

 

   //Select all String Starting with 'a' using LINQ

 

   IEnumerable<string> result = from str in StringArray where str[0] == 'a' orderby str.Length select str;

 

   //Display result in List Box

   listBox1.Items.Clear();

   foreach (string str in result)

   {

        listBox1.Items.Add(str);

   }

}


Conclusion


We have just seen in this article about how to manipulate array and collections using LINQ.

erver'>

Similar Articles