How to create LINQ queries to filter the elements of an array of objects
This complete sample shows how to create LINQ queries in a C# application to filter the elements of an array of objects.
Code:
using System;
using System.Linq;
namespace ConsoleApplications
{
class ArrayLinqDemo
{
static void Main(string[] args)
{
// Create an array of type object Fruit
Fruit[] fruits = new Fruit[7];
fruits[0] = new Fruit("Ananas", 14, 10);
fruits[1] = new Fruit("Apple", 8, 3);
fruits[2] = new Fruit("Mango", 5, 16);
fruits[3] = new Fruit("Orange", 23, 18);
fruits[4] = new Fruit("Lemon", 9, 12);
fruits[5] = new Fruit("Papaya", 11, 3);
fruits[6] = new Fruit("Raspberry", 33, 23);
Console.WriteLine("All elements of the array");
foreach (Fruit f in fruits)
{
Console.WriteLine( f.ToString() );
}
// Select the fruit whose name starts with A
Console.WriteLine();
Console.WriteLine("Select the fruit whose name starts with A");
var queryByName =
from fruit in fruits
where (fruit.Name.StartsWith("A"))
orderby fruit.Name ascending
select fruit;
foreach (Fruit f in queryByName)
Console.WriteLine("{0}", f.ToString());
// Select the fruits whose amount is less than 10
Console.WriteLine();
Console.WriteLine("Select the fruits whose amount is less than 10");
var queryByQuantity =
from fruit in fruits
where (fruit.Amount<10)
orderby fruit.Amount ascending
select fruit;
foreach (Fruit f in queryByQuantity)
Console.WriteLine("{0}", f.ToString());
// Extract the fruit whose weight is greater than 10
Console.WriteLine();
Console.WriteLine("Extract the fruit whose weight is greater than 10");
var queryByWeight =
from fruit in fruits
where (fruit.Weight > 10)
orderby fruit.Weight ascending
select fruit;
foreach (Fruit f in queryByWeight)
Console.WriteLine("{0}", f.ToString());
}
}
/// <summary>
/// A simple class to represent the fruits
/// </summary>
class Fruit
{
private string name;
private int amount;
private int weight;
public string Name
{
get{ return name;}
set { name = value; }
}
public int Amount
{
get { return amount; }
set { amount = value; }
}
public int Weight
{
get { return weight; }
set { weight = value; }
}
public Fruit(string n, int a, int w)
{
name = n;
amount = a;
weight = w;
}
public new string ToString()
{
return String.Format("{0} ({1}), [{2}]",name, amount, weight);
}
}
}
Result:
All elements of the array
Ananas (14), [10]
Apple (8), [3]
Mango (5), [16]
Orange (23), [18]
Lemon (9), [12]
Papaya (11), [3]
Raspberry (33), [23]
Select the fruit whose name starts with A
Ananas (14), [10]
Apple (8), [3]
Select the fruits whose amount is less than 10
Mango (5), [16]
Apple (8), [3]
Lemon (9), [12]
Extract the fruit whose weight is greater than 10
Lemon (9), [12]
Mango (5), [16]
Orange (23), [18]
Raspberry (33), [23]