Language-Integrated Queries: LINQ
Objective: Use Linq to explore a list of items.
Create a new empty game object, Item_Manger, and add a new script ItemManager. Make sure to add the using System.Linq namespace. Within this script, create a new class Item which has three variables a string name, an int itemID and int buff. Make this class system serializable so that it can assigned in the inspector.
Create a new public Item list, items, as shown below.
The items are assigned in the inspector as shown below.
One useful method in Linq is Any, which searches an Enumerable for a defined element. In the example below the items list is searched to see if each item’s itemID is three. The method returns a bool, in this case true, as the staff does indeed exist. From the syntax below, Linq methods are identifiable as functions, Func, for which the functions can be defined using the => or lambda expression.
Another useful Linq method is the Where function, which selects a subset of the list based upon user defined rule. In the example below, items with a buff > 20 are assigned to a new list bigBuffItems. Each item’s buff is checked within the items list, and if >20 is added to the new list.
Linq contains a number of numeric functions such as Sum, Max, Min and Range. For this article, Average will be used as an example. The decimal variable to be average is specified, in this case buff, and the average is returned and assigned to buffMean, which is 20.2f.
A few other Linq methods worth mentioning are OrderBy for sorting elements, Reverse to reverse element order, Contains to checking element is in list and Distinct to remove duplicates. Linq has a large number of functions available for parsing lists and arrays, which can be found at the link below.