Reader small image

You're reading from  Learning C# by Developing Games with Unity - Seventh Edition

Product typeBook
Published inNov 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781837636877
Edition7th Edition
Languages
Tools
Right arrow
Author (1)
Harrison Ferrone
Harrison Ferrone
author image
Harrison Ferrone

Harrison Ferrone is an instructional content creator for LinkedIn Learning and Pluralsight, tech editor for the Ray Wenderlich website, and used to write technical documentation on the Mixed Reality team at Microsoft. He is a graduate of the University of Colorado at Boulder and Columbia College, Chicago. After a few years as an iOS developer at small start-ups, and one Fortune 500 company, he fell into a teaching career and never looked back.
Read more about Harrison Ferrone

Right arrow

Specialized Collection Types and LINQ

In the last chapter, we revisited variables, types, and classes to see what they had to offer beyond the basic features introduced at the beginning of the book. In this chapter, we’ll take a closer look at new collection types and learn about their intermediate-level capabilities and how to filter, order, and transform data with LINQ queries.

Remember, being a good programmer isn’t about memorizing code; it’s about choosing the right tool for the right job. Each of the new collection types in this chapter has a specific purpose. For most scenarios where you need a collection of data, a list or array works just fine. However, when you need temporary storage or control over the order of collection elements, or more specifically, the order they are accessed, look to stacks and queues. When you need to perform operations that depend on every element in a collection to be unique, meaning not duplicated, look to HashSets. Before...

Introducing stacks

At its most basic level, a stack is a collection of elements of the same specified type. The length of a stack is variable, meaning it can change depending on how many elements it’s holding. The important difference between a stack and a list or array is how the elements are stored. While lists or arrays store elements by index, stacks follow the last-in-first-out (LIFO) model, meaning the last element in the stack is the first accessible element. This is useful when you want to access elements in reverse order. You should note that they can store null and duplicate values. A helpful analogy is a stack of plates—the last plate you put on the stack is the first one you can easily get to. Once it’s removed, the next-to-last plate you stacked is accessible, and so on.

All the collection types in this chapter are a part of the System.Collections.Generic namespace, meaning you need to add the following code to the top of any file that...

Working with queues

Like stacks, queues are collections of elements or objects of the same type. The length of any queue is variable just like a stack, meaning its size changes as elements are added or removed. However, queues follow the first-in-first-out (FIFO) model, meaning the first element in the queue is the first accessible element. You should note that queues can store null and duplicate values but can’t be initialized with elements when they’re created. The code in this section is for example purposes only and is not included in our game.

A queue variable declaration needs to have the following:

  • The Queue keyword, its element type between left and right arrow characters, and a unique name
  • The new keyword to initialize the queue in memory, followed by the Queue keyword and element type between arrow characters
  • A pair of parentheses capped off by a semicolon

In blueprint form, a queue looks as follows:

Queue<elementType...

Using HashSets

The last collection type we’ll get our hands on in this chapter is the HashSet. This collection is very different from any other collection type that we’ve come across: it cannot store duplicate values and is not sorted, meaning its elements are not ordered in any way. Think of HashSets as dictionaries with just keys, instead of key-value pairs.

They can perform set operations and element lookups extremely fast, which we’ll explore at the end of this section, and are best suited to situations where the element order and uniqueness are a top priority.

A HashSet variable declaration needs to meet the following requirements:

  • The HashSet keyword, its element type between left and right arrow characters, and a unique name
  • The new keyword to initialize the HashSet in memory, followed by the HashSet keyword and element type between arrow characters
  • A pair of parentheses capped off by a semicolon

In blueprint form...

Intermediate collections roundup

Before you move on, let’s drive home some key points from what we’ve just learned. Topics that don’t always have a 1-to-1 relationship with the actual game prototype we’re building need a little extra love sometimes. The one question I’m sure you’re asking yourself at this point is: why use any of these other collection types when I could just use lists for everything? And that’s a perfectly valid question. The easy answer is that stacks, queues, and HashSets offer better performance than lists when applied in the correct circumstances. For example, when you need to store items in a specific order, and access them in a specific order, a stack would be more efficient than a list.

The more complicated answer is that using different collection types enforces how your code is allowed to interact with them and their elements. This is a mark of good code design, as it removes any ambiguity on how you&...

Querying data with LINQ

We’ve covered a few different ways to store elements, or sequences of values, in this chapter—the one thing we haven’t talked about is how to get specific subsets of data back out. So far, our game’s loot is stored in a Stack variable, and we can always pop off the next loot element in the order they are stored, but that doesn’t help us when we want to filter down the stack (or any other collection type we’ve discussed in this book) to specific elements that fit predefined criteria.

For example, say we wanted to get a list of all the elements in the Loot stack with a rarity value of 3 or more. We could absolutely use a looping statement, but that leads to a lot of code and manual checks if we wanted to add more parameters to our filter. Instead, C# has a specific set of features for querying data called LINQ, which stands for Language Integrated Query. LINQ is fast, efficient, and, most importantly, customizable...

Summary

Congratulations, you’re almost at the finish line! In this chapter, you learned about three new collection types, and how they can be used in different situations.

Stacks are great if you want to access your collection elements in the reverse order that they were added, queues are your ticket if you want to access your elements in sequential order, and both are ideal for temporary storage. The important difference between these collection types and lists or arrays is how they can be accessed with popping and peeking operations. Lastly, you learned about the almighty HashSet and its performance-based mathematical set operations. In situations where you need to work with unique values and perform additions, comparisons, or subtractions on large collections, these are key.

In the next chapter, you’ll be taken a little deeper into the intermediate world of C# with delegates, generics, and more as you approach the end of this book. Even after all you’...

Pop quiz—intermediate collections

  1. Which collection type stores its elements using the LIFO model?
  2. Which method lets you query the next element in a stack without removing it?
  3. Can stacks and queues store null values?
  4. How would you subtract one HashSet from another?

Don’t forget to check your answers against mine in the Pop Quiz Answers appendix to see how you did!

Join us on discord!

Read this book alongside other users, Unity game development experts and the author himself.

Ask questions, provide solutions to other readers, chat with the author via. Ask Me Anything sessions and much more.

Scan the QR code or visit the link to join the community.

https://packt.link/csharpwithunity

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning C# by Developing Games with Unity - Seventh Edition
Published in: Nov 2022Publisher: PacktISBN-13: 9781837636877
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Harrison Ferrone

Harrison Ferrone is an instructional content creator for LinkedIn Learning and Pluralsight, tech editor for the Ray Wenderlich website, and used to write technical documentation on the Mixed Reality team at Microsoft. He is a graduate of the University of Colorado at Boulder and Columbia College, Chicago. After a few years as an iOS developer at small start-ups, and one Fortune 500 company, he fell into a teaching career and never looked back.
Read more about Harrison Ferrone