Introduction
LINQ provides extensive flexiblity in the implementation of queries across objects with thrilling ease and readibility of code.
The following simple project shows use of linq to object for extracting and showing data whenever needed.
First we created ShoppingCartUsingLinq class with three automatic properties; ProductName, ProductPrice and NumberOfUnits. Secondly, we decalre List<> object of type ShoppingCartDemo1 class, whenever the addToShoppingCart Button clicked the list will be populated with associated properties from every ComboBox that host the specific values related to these properties.
At last, linq comes to play here to provide its stunning functionality to extract all properties to every object to be shown in listBox1, in addition the aggregate extension method of linq will present the total sum of money has to be paid.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace LinqToObjectExample
{
public partial class Form1 : Form
{
// decalre List<> object of type ShoppingCartDemo1 class
List<ShoppingCartUsingLinq> ShoppingCartDemo1 = new List<ShoppingCartUsingLinq>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void addToShoppingCart_Click(object sender, EventArgs e)
{
// Add ShoppingCartUsingLinq object to ShoppingCartDemo1 list
ShoppingCartDemo1.Add(new ShoppingCartUsingLinq { ProductName = comboBox1.SelectedItem.ToString(), ProductPrice = Convert.ToDouble(comboBox2.SelectedItem), NumberOfUnits=Convert.ToInt32(comboBox3.SelectedItem) });
// using linq to query ShoppingCartUsingLinq class properties
var q = from w in ShoppingCartDemo1
select string.Format(" ProductName: {0} ProductPrice: {1} NumberOfUnits: {2}", w.ProductName, w.ProductPrice,w.NumberOfUnits);
//Populate listBox1 with all ShoppingCartUsingLinq properties
listBox1.Items.Clear();
listBox1.Items.AddRange(q.ToArray());
listBox1.Items.Add("");
// using linq to calculate price of every product
var price = from w in ShoppingCartDemo1
select (w.ProductPrice * w.NumberOfUnits);
// using linq to calculate the total price by using aggregate extension method
double[] AllPrices = price.ToArray();
double sum = AllPrices.Aggregate((a, b) => a + b);
textBox1.Text = sum.ToString();
}
}
// ShoppingCartUsingLinq class
public class ShoppingCartUsingLinq
{
public ShoppingCartUsingLinq()
{
}
// Automatic properties of ShoppingCartUsingLinq
public string ProductName { get; set; }
public double ProductPrice { get; set; }
public int NumberOfUnits { get; set; }
}
}