Loading...

C# LINQ

Ask three numbers one question and print the answer. LINQ is the set of methods that ask that kind of question. Here the question is "which numbers are above 5?" The array holds 3, 12, and 8. Where keeps 12 and 8. Sum adds them to 20. The lambda from the last page turns that into pine x20.
The lambda page printed pine, then 12, then pine x12. Those three lines stay first, in the same order, from the same Hold objects and the same label. Optional Advanced continues, so Pine, Hold<T>, and Item do not change. Two new lines go under them. If dotnet run still stops at pine x12, the new WriteLine calls are missing or dotnet run --no-build is running the lambda program.

One array, one question

Open PineLab. Keep Hold<T>, the two holders, and label. Add one line at the top, under using System;:
using System.Linq;
Where, ToArray, and Sum live in that namespace. They are extension methods: they look like methods on the array, but the namespace brings them in. Many new console projects already turn on implicit usings, which include System.Linq. This file writes the line anyway, so it does not depend on that project setting.
Under label, build the array. The middle value is the held number, not a new literal:
int[] counts = { 3, number.Item, 8 };
Then ask the question and keep the answer:
int[] big = counts.Where(n => n > 5).ToArray();
n => n > 5 is a lambda, the same arrow as last time. It takes one int and returns a bool. One parameter, so it has no parentheses. Where calls it once for each number and keeps the ones where it returns true.
Print the old three lines, then the two new ones:
Console.WriteLine(string.Join(",", big));
Console.WriteLine(label(word.Item, big.Sum()));

Hold and the lambda, plus one Where over three numbers

csharp
using System;
using System.Linq;

public class Hold<T>
{
    public T Item;

    public Hold(T item)
    {
        Item = item;
    }
}

public class Pine
{
    public static void Main()
    {
        Hold<string> word = new Hold<string>("pine");
        Hold<int> number = new Hold<int>(12);
        Func<string, int, string> label = (name, count) => name + " x" + count;
        int[] counts = { 3, number.Item, 8 };
        int[] big = counts.Where(n => n > 5).ToArray();
        Console.WriteLine(word.Item);
        Console.WriteLine(number.Item);
        Console.WriteLine(label(word.Item, number.Item));
        Console.WriteLine(string.Join(",", big));
        Console.WriteLine(label(word.Item, big.Sum()));
    }
}

Five lines

Run dotnet run from PineLab. The screen shows pine, 12, pine x12, then 12,8, then pine x20.
The first three lines are the lambda page, unchanged. The fourth line is the kept numbers. 3 fails the test, because 3 is not above 5. 12 passes. 8 passes. Where keeps the order of the array, so the line is 12,8, not 8,12. string.Join puts a comma between them and no space. The fifth line is the same label as the third line, with a different number. big.Sum() is 12 plus 8, which is 20.
counts itself does not change. It still holds 3, 12, and 8. Where builds a new sequence and leaves the array alone. number.Item is still 12, and the third line still says pine x12.
The 12 on the fourth line is the held number. It came from number.Item when the array was built. If you change the holder to new Hold<int>(4), the second line becomes 4, the third becomes pine x4, 4 fails the test, the fourth line becomes 8, and the fifth becomes pine x8. Put 12 back.

What each call does

Where alone does not filter yet. It returns a query that waits until something asks for its items. ToArray asks for every item now and stores them in a new array. After that line, big is a plain int[] with two values. Sum adds the values in big.
That waiting matters when the array changes. If you dropped ToArray and kept the bare query, then set counts[0] = 9 before printing, the printed numbers would be 9,12,8, because the query runs when string.Join reads it. With ToArray, the answer is fixed at the line where you asked. The checked file never changes counts, so both forms print the same five lines here. Keep ToArray anyway, so big has a type you already know, int[], and the order of lines does not change the answer.

📊 Three LINQ calls in this file

Call What it gives in this file
Where a query that keeps 12 and 8 from 3, 12, 8
ToArray runs the query now and stores 12 and 8 in big
Sum adds 12 and 8 and gives 20

Change the question

Change n > 5 to n > 10. Only 12 passes. After dotnet run the fourth line is 12 and the fifth is pine x12. The fifth line now matches the third, because the only kept number is the held one. Change it back.
Change it to n > 12. Nothing passes, because 12 is not above 12. big is an empty array. The fourth line is empty, and the fifth is pine x0, because the sum of no numbers is 0. Nothing throws. Change it back to n > 5.
n >= 3 keeps all three. The fourth line is 3,12,8 and the fifth is pine x23. That is not the checked file. Put n > 5 back before you compare the five lines.
The lambda inside Where must return a bool. counts.Where(n => n + 1) returns an int from the lambda, and the build fails. None of the five lines appear.

Things this file leaves out

LINQ also has a query form that reads like a sentence: from n in counts where n > 5 select n. It does the same filtering. This page uses only the method form, counts.Where(...), so the lambda stays visible. Do not mix both forms in this file.
Select changes each item. OrderBy sorts. First takes one item. They are real LINQ methods, and none of them are in the checked file. A sixth line means you added one. Remove it before you judge the screen.
The array is not a List<int>. LINQ works on both, but the list page already used a list, and this file keeps one small array so the three values are easy to read. You do not need new List<int> here.
Hold stays a single value holder. LINQ runs on counts, not on word or number. word.Where(...) does not make sense, because a Hold<string> is not a sequence.

Records come next

You can keep the three lines from the lambda page and add an answer from one LINQ question under them. The next page is records. A record is a type that holds values and compares them by content, written with the keyword record. This page stops before that. There is no record in this file, and Hold stays a class.
One last pass: using System.Linq; under using System;, Hold<T> unchanged, label unchanged, counts with 3, number.Item, and 8, one Where with n > 5, ToArray, Sum inside the last call, no Select and no OrderBy. dotnet run shows pine, 12, pine x12, 12,8, and pine x20. When those five lines match, LINQ did its one job here.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top