Example of how to filter the elements of an array with LINQ in C#, based on the criteria
The first query selects all the fruit whose name begins with a letter from A to L, the second query selects all the fruit whose name begins with a letter from M to Z.
Code:
using System;
using System.Linq;
namespace ConsoleApplications
{
class ArrayLinqDemo
{
static void Main(string[] args)
{
string[] al = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L" };
string[] mz = { "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
// 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~L
Console.WriteLine();
Console.WriteLine("Select the fruit whose name starts with A~L");
var queryByNameAL =
from fruit in fruits
where ( al.Contains(fruit.Name.Substring(0,1)) )
orderby fruit.Name ascending
select fruit;
foreach (Fruit f in queryByNameAL)
Console.WriteLine("{0}", f.ToString());
// Select the fruit whose name starts with M~Z
Console.WriteLine();
Console.WriteLine("Select the fruit whose name starts with M~Z");
var queryByNameMZ =
from fruit in fruits
where (mz.Contains(fruit.Name.Substring(0, 1)))
orderby fruit.Name ascending
select fruit;
foreach (Fruit f in queryByNameMZ)
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~L
Ananas (14), [10]
Apple (8), [3]
Lemon (9), [12]
Select the fruit whose name starts with M~Z
Mango (5), [16]
Orange (23), [18]
Papaya (11), [3]
Raspberry (33), [23]