- CRUD Operations With Web API Using ...
- Retrieve Followed Sites in SharePoi ...
- How to Check Whether API Server is ...
- Shortcuts in Visual Studio that are ...
- MVC For Beginners: Day 1 (Controller)
- A New Era of Smartphone: Google ARA
- MVC For Beginners: Day 2 (View)
- Here is How to Work in the USA
- Angular JS Filter, Sorting and Anim ...
- Draw ASP.Net Chart Using HTML5 and ...

# Think in LINQ: Yahtzee Score Calculator Using LINQ Technology

- 0
- 0
- 17018

This is an update of the Yahtzee game I wrote back in 2002 which replaces the **ScoreCalculator** class with methods that use LINQ queries on the dice array. In order to use LINQ, you'll need to download a preview of LINQ functionality into Visual Studio from Microsoft. LINQ takes some getting used to, because you have to alter your thought process a little in order to write the code for filtering, grouping, sorting, and examining collections. However, once you get the hang of it, the code you write is greatly reduced and much cleaner.

LINQ can be broken down into about 14 different operator groups. Below are most of the commonly used ones:

Table 1 - Operators built into LINQ

Operator | Definition | Keyword |

Filter | Restricts the data in a collection with a condition | Where, OfType |

Select | Selects specific items from a collection as well as being able to select generated and calculated items. | Select, SelectMany |

Partitioning | Chooses portions of a collection based on the index in the sequence. | Take, Skip |

Sorting | Puts the collection in order | OrderBy, OrderByDescending, ThenBy, ThenByDescending, Reverse |

Grouping | Groups the items in a collection into a collection of groups | GroupBy |

Set Operations | Does Set operations on one or more collections | Distinct, Union, Intersect, Except |

Conversion | Converts the IEnumerable<> collection to another collection type | ToArray, ToList, ToDictionary |

Single Element | Accesses an individual element in the collection | First, ElementAt |

Aggregate/Statistical functions | Performs a function on the collection to obtain statistical data for the whole collection | Count, Sum, Min, Max, Average, Fold |

Quantifiers | Returns a boolean to determine if the items in the collection meet the functions criteria | Any, All, EqualAll |

In the article to follow, we'll use some of these functions in our yahtzee score calculator to determine a score in a particular row on the yahtzee board.

**Out with the Old, In with the New**

Let's look at one of the scoring challenges. In yahtzee, there is a column for each number on the die. The row with a particular die number is scored by the total of the dice displaying that number. So, for example, let's say you roll the five dice, and 4 three's appear on 4 of the 5 dice, a sample roll might be {3, 4, 3, 3, 3}. If you put this score in the three's row, then you would get a score of 4 x 3 = 12. How do we handle calculating the score for matching die in code?

Let's first think about what we want to accomplish in order to understand the code implementation. We want to extract all the dice from the collection with the die number equal to nDie. Then we want to add them up.

**Old Method:**

Normally we we would loop through all values in the dice collection and use an **if statement** to determine if the die were equal to nDie. If the die was equal to nDie, we would add the die to a total sum that was initialized to zero.

**LINQ Method:**

Run a query on the dice collection that filters all die = nDie using a **Where** clause. Take the results of this query and call a **Sum** function to sum the matching die.

**Listing 1 - Calculating matching Dice Rolls using LINQ**

public int CalculateLikeRolls(int nDie, Dice[] dice) { // determine all the dice in the dice collection // that have the value of nDie var numberOfValues = from die in dice where die.RollNumber == nDie select die.RollNumber;// Add all the values which have value nDie together int sum = numberOfValues.Sum(); // add the sum to the total score and to the upper // score section m_nTotal += sum; m_nUpperTotal += sum; return sum; } |

Although this isn't a large difference in the amount of code, it is a lot cleaner and brings us to a higher level of thinking about how we milk our collection data for useful information. Also, (as you'll see in the following yahtzee calculations), LINQ reduces our code by quite a bit.

Let's take a look at another yahtzee score: three of a kind. With three of a kind, if you have at least 3 of the same die value out of 5 die, you can sum the die together for the score and put it in the three of a kind column. How do we score this in code?

**Old Method:**

Somehow we need to determine which items in the collection are alike. One way to do this is to build a Hashtable containing a histogram of all 6 (1-6) die possibilities as keys. We increment each hash key each time a die matches that key. If one of the keys is equal to or greater than 3, then we loop through all the dice and sum them.

**LINQ Method:**

**Group** all the dice by like numbers and count them in a generated DieCount collection. Determine if there is **Any** group containing at least 3 dice. If so, **Sum** the dice. You can start to see how the solution to the problem more closely matches your thinking in the implementation of the solution.

**Listing 2 - Calculating Three of A Kind using LINQ**

public int CalculateThreeOfAKind (Dice[] myDice) { // group the die by dice number and keep a count of each group // determine if there is at least 3 dice in any group // if not, then there is no score // yes, we have three of a kind, sum all the dice |

Finally, let's look at how to score a large straight. A large straight is a set of 5 consecutive die values (either a roll of {1, 2, 3, 4, 5} or a roll of {2,3,4,5,6})

**Old Method:**

One way to determine if you have a large straight is to sort all the die in an ArrayList, then loop through each die and determine if the die in front of the previous die is at least 1 ahead of the previous die. Another way would be to sort all the die in order, then loop through each of the two possible large straight arrays and test each die against the corresponding element at the same index to see if they are the same.

**LINQ Method:**

See if one of the two possible straights {1, 2, 3, 4, 5} and {2,3,4,5,6} **Intersect** with all 5 dice in the roll.

**Listing 3 - Calculating a Large Straight using LINQ**

public int CalculateLargeStraight (Dice[] myDice) { // now test against 2 possibilities // get the dice as a result of integers var result = from die in myDice orderby die.RollNumber select die.RollNumber; // possible large straights int[] largeStraight1 = new int[5]{1,2,3,4,5}; int[] largeStraight2 = new int[5]{2,3,4,5,6}; // test to see if the roll intersects all 5 dice in either of the two possibilities |

**Conclusion:**

LINQ is a powerful technology for manipulating collections that will require you to change your thinking of how you are probably currently manipulating them in C#. Not only can LINQ help you query and manipulate collections in memory, but LINQ technology can be extended to work with databases (DLINQ) and XML (XLINQ). Ultimately, LINQ reduces code size and helps your code implementation match a higher level thinking of working with the data. In the meantime, if you are in search for the *missing LINQ*, you may have found it here in C# and .NET 3.0.

Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE ... Read more

- rank19
- 17 m readers
- PlatinumMember
- 1 times
- times