Free Unity Tutorials

C# LINQ

Visual Studio, C# Console Application: System.LINQ

by Charles Burt on 28/07/2019

Play Video

The Problem:
Have you ever needed to grab elements from an array, list or any type of collection, put them into a new collection, in a specific order?

The Solution:
LINQ allows you to do all of this by using 4 simple keywords: 

  1. from
  2. where
  3. orderby
  4. select

Steps:
Implementation Steps start from 2 minutes 50 seconds into the video above.

using System;
using System.Linq;

class Program
{

    class Fruit
    {
        public int DaystToExpiry;

        private string m_fruitName;
        public string FruitName
        {

            get { return "Fruit Name: " + m_fruitName; }
            set { m_fruitName = value; }

        }

    }

    static void Main(string[] args)
    {

        Fruit[] food =
        {

            new Fruit { FruitName = "0 Apple", DaystToExpiry = 12 },
            new Fruit { FruitName = "1 Pear", DaystToExpiry = 11 },
            new Fruit { FruitName = "2 Apple", DaystToExpiry = 10 }

        };


        //foreach (var item in food)
        //{
        //    if(item.FruitName.Contains("Apple"))
        //        Console.WriteLine(item.FruitName + " Days to expiry: " + item.DaystToExpiry);

        //}
        
        var fruitQuery = from f in food
                          where f.FruitName.Contains("Apple")
                          orderby f.DaystToExpiry
                          select f;

        foreach (var item in fruitQuery)
        {

            Console.WriteLine(item.FruitName + " Days left until expiry: " + item.DaystToExpiry);

        }
        
    }

}



LINQ Method Query Syntax

//var fruitQuery = from f in fruitArray
//                 where f.FruitName.Contains("Apple")
//                 orderby f.DaystToExpiry
//                 select f;


var fruitMethodQuery = fruitArray.Where(f => f.FruitName.Contains("Apple")).OrderBy(f => f.DaystToExpiry);

//bool FruitNameContains(Fruit f) => f.FruitName.Contains("Apple"); 



LINQ Data Filtering

using System;
using System.Linq;

class Program
{

    class Fruit
    {
        public string SupplierName;

        public int AvailableStock;
        public int DaystToExpiry;

        public enum LocationEnum
        {
            London,
            NewYork,
            Paris
        }
        public LocationEnum SupplierLocation;

        private string m_fruitName;
        public string FruitName
        {

            get { return "Fruit Name: " + m_fruitName; }
            set { m_fruitName = value; }

        }

    }

    static void Main(string[] args)
    {

        Fruit[] fruitArray =
        {

            new Fruit { FruitName = "Apple", DaystToExpiry = 12, SupplierLocation = Fruit.LocationEnum.London, SupplierName = "Tesco", AvailableStock = 10 },
            new Fruit { FruitName = "Pear", DaystToExpiry = 11, SupplierLocation = Fruit.LocationEnum.London, SupplierName = "Lidl", AvailableStock = 5  },
            new Fruit { FruitName = "Apple", DaystToExpiry = 10, SupplierLocation = Fruit.LocationEnum.Paris, SupplierName = "Sainsburies", AvailableStock = 1  },
            new Fruit { FruitName = "Apple", DaystToExpiry = 11, SupplierLocation = Fruit.LocationEnum.NewYork, SupplierName = "Costco", AvailableStock = 90  },
            new Fruit { FruitName = "Apple", DaystToExpiry = 5, SupplierLocation = Fruit.LocationEnum.NewYork, SupplierName = "Wall Mart", AvailableStock = 1  }

        };

        //--------------------------------------
        //I want to get a list of all the FruitNames that have the supplier location of london
        //var fruitMethodQuery = fruitArray.Where(f => f.SupplierLocation == Fruit.LocationEnum.London);

        //foreach (var item in fruitMethodQuery)
        //{
        //    Console.WriteLine(item.FruitName + " Days left until expiry: " + item.DaystToExpiry + " Supplier Location: " + item.SupplierLocation);
        //}

        //--------------------------------------
        //I want to find out how many suppliers are based in Paris
        //var fruitMethodQuery = fruitArray.LongCount(f => f.SupplierLocation == Fruit.LocationEnum.Paris);
        //Console.WriteLine("Suppliers based in Paris: " + fruitMethodQuery);

        //--------------------------------------
        //I need a list of supplier names that have apple stock levels with at least 10 days left until expiry and at least 10 in stock, ordered by the freshest apples
        //var suppliers = fruitArray.Where(f => f.DaystToExpiry >= 10).Where(f => f.AvailableStock >= 10).OrderBy(f => f.DaystToExpiry);
        //foreach (var item in suppliers)
        //{
        //    Console.WriteLine(item.SupplierName);
        //}

        //--------------------------------------
        //I need the maximum number of Apples available in all suppliers
        //var maxApplesAvailable = fruitArray.Sum(f => f.AvailableStock);
        //Console.WriteLine(fruitArray.Sum(f => f.AvailableStock));

        //--------------------------------------
        //I want a new array of that only includes the suppliers' names
        //var suppliersNameArray = fruitArray.Select(f => f.SupplierName).ToArray();
        //foreach (var item in suppliersNameArray)
        //{
        //    Console.WriteLine(item);
        //}

        //--------------------------------------
        //I want a new array that includes the suppliers' names and the suppliers' location
        //var suppliersNameLocArray = fruitArray.Select(f => new { f.SupplierName, f.SupplierLocation });
        //foreach (var item in suppliersNameLocArray)
        //{
        //    Console.WriteLine(item.SupplierName + " " + item.SupplierLocation);
        //}

        //--------------------------------------
        //I want a new dictionary that uses the suppliers name as the key and the suppliers location as the value
        //var suppliersNameLocDictionary = fruitArray.ToDictionary(f => f.SupplierName, f => f.SupplierLocation);
        //foreach (var item in suppliersNameLocDictionary)
        //{
        //    Console.WriteLine("Key: " + item.Key + " Value: " + item.Value);
        //}
    }

}


Links

Share

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
Charles_Burt

Charles Burt

Unity Developer

Author Bio

This tutorial was written by me, Charles Burt. Nice to meet you!

I have over a decade of experience in creating software using the Unity Editor and setting up teams around projects.

If you have a project you need help with, or know someone that does, click the HIRE ME button at the bottom of the page! 

Thank you and I hope you found this tutorial helpful.