برچسب: sequence

  • LINQ’s Enumerable.Range to generate a sequence of consecutive numbers | Code4IT

    LINQ’s Enumerable.Range to generate a sequence of consecutive numbers | Code4IT


    Just a second! 🫷
    If you are here, it means that you are a software developer.
    So, you know that storage, networking, and domain management have a cost .

    If you want to support this blog, please ensure that you have disabled the adblocker for this site.
    I configured Google AdSense to show as few ADS as possible – I don’t want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

    Thank you for your understanding.
    Davide

    When you need to generate a sequence of numbers in ascending order, you can just use a while loop with an enumerator, or you can use Enumerable.Range.

    This method, which you can find in the System.Linq namespace, allows you to generate a sequence of numbers by passing two parameters: the start number and the total numbers to add.

    Enumerable.Range(start:10, count:4) // [10, 11, 12, 13]
    

    ⚠ Notice that the second parameter is not the last number of the sequence. Rather, it’s the length of the returned collection.

    Clearly, it also works if the start parameter is negative:

    Enumerable.Range(start:-6, count:3) // [-6, -5, -4]
    

    But it will not work if the count parameter is negative: in fact, it will throw an ArgumentOutOfRangeException:

    Enumerable.Range(start:1, count:-23) // Throws ArgumentOutOfRangeException
    // with message "Specified argument was out of the range of valid values"(Parameter 'count')
    

    ⚠ Beware of overflows: it’s not a circular array, so if you pass the int.MaxValue value while building the collection you will get another ArgumentOutOfRangeException.

    Enumerable.Range(start:Int32.MaxValue, count:2) // Throws ArgumentOutOfRangeException
    

    💡 Smart tip: you can use Enumerable.Range to generate collections of other types! Just use LINQ’s Select method in conjunction with Enumerable.Range:

    Enumerable.Range(start:0, count:5)
        .Select(_ => "hey!"); // ["hey!", "hey!", "hey!", "hey!", "hey!"]
    

    Notice that this pattern is not very efficient: you first have to build a collection with N integers to then generate a collection of N strings. If you care about performance, go with a simple while loop – if you need a quick and dirty solution, this other approach works just fine.

    Further readings

    There are lots of ways to achieve a similar result: another interesting one is by using the yield return statement:

    🔗 C# Tip: use yield return to return one item at a time | Code4IT

    This article first appeared on Code4IT 🐧

    Wrapping up

    In this C# tip, we learned how to generate collections of numbers using LINQ.

    This is an incredibly useful LINQ method, but you have to remember that the second parameter does not indicate the last value of the collection, rather it’s the length of the collection itself.

    I hope you enjoyed this article! Let’s keep in touch on Twitter or on LinkedIn, if you want! 🤜🤛

    Happy coding!

    🐧





    Source link

  • List Pattern to match an collection against a sequence of patterns | Code4IT

    List Pattern to match an collection against a sequence of patterns | Code4IT


    By using list patterns on an array or a list you can check whether a it contains the values you expect in a specific position.

    Table of Contents

    Just a second! 🫷
    If you are here, it means that you are a software developer.
    So, you know that storage, networking, and domain management have a cost .

    If you want to support this blog, please ensure that you have disabled the adblocker for this site.
    I configured Google AdSense to show as few ADS as possible – I don’t want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

    Thank you for your understanding.
    Davide

    With C# 11 we have an interesting new feature: list patterns.

    You can, in fact, use the is operator to check if an array has the exact form that you expect.

    Take this method as an example.

    Introducing List Patterns

    string YeahOrError(int[] s)
    {
        if (s is [1, 2, 3]) return "YEAH";
        return "error!";
    }
    

    As you can imagine, the previous method returns YEAH if the input array is exactly [1, 2, 3]. You can, in fact, try it by running some tests:

    [Test]
    public void PatternMatchingWorks()
    {
        Assert.That(YeahOrError(new int[] { 1, 2, 3 }), Is.EqualTo("YEAH"));
        Assert.That(YeahOrError(new int[] { 1, 2, 3, 4 }), Is.EqualTo("error!"));
        Assert.That(YeahOrError(new int[] { 2, 3, 1}), Is.EqualTo("error!"));
    }
    

    As you can see, if the order is different, the check does not pass.

    List Patterns with Discard

    We can also use discard values to check whether a list contains a specific item in a specified position, ignoring all the other values:

    string YeahOrErrorWithDiscard(int[] s)
    {
        if (s is [_, 2, _]) return "YEAH";
        return "error!";
    }
    

    So, to be valid, the array must have exactly 3 elements, and the second one must be a “2”.

    [Test]
    public void PatternMatchingWorksWithDiscard()
    {
        Assert.That(YeahOrErrorWithDiscard(new int[] { 1, 2, 3 }), Is.EqualTo("YEAH"));
        Assert.That(YeahOrErrorWithDiscard(new int[] { 9, 2, 6 }), Is.EqualTo("YEAH"));
        Assert.That(YeahOrErrorWithDiscard(new int[] { 1, 6, 2, 3 }), Is.EqualTo("error!"));
        Assert.That(YeahOrErrorWithDiscard(new int[] { 6, 3, 8, 4 }), Is.EqualTo("error!"));
    }
    

    List Patterns with variable assignment

    You can also assign one or more of such values to a variable, and discard all the others:

    string SelfOrMessageWithVar(int[] s)
    {
        if (s is [_, 2, int third]) return "YEAH_" + third;
        return "error!";
    }
    

    The previous condition, s is [_, 2, int third], returns true only if the array has 3 elements, and the second one is “2”. Then, it stores the third element in a new variable, int third, and uses it to build the returned string.

    [Test]
    public void can_use_list_patterns_with_var()
    {
        Assert.That(SelfOrMessageWithVar(new int[] { 1, 2, 3 }), Is.EqualTo("YEAH_3"));
        Assert.That(SelfOrMessageWithVar(new int[] { 1, 6, 2, 3 }), Is.EqualTo("error!"));
        Assert.That(SelfOrMessageWithVar(new int[] { 6, 3, 8, 4 }), Is.EqualTo("error!"));
    }
    

    List Patterns with item constraints

    Finally, you can also specify further constraints on each value in the condition, using operators such as or, >, >=, and so on.

    string SelfOrMessageWithCondition(int[] s)
    {
        if (s is [0 or 1, > 2, int third]) return "YEAH_" + third;
        return "error!";
    }
    

    You can easily guess the meaning of the previous method. You can double-check the actual result by looking at the following tests:

    [Test]
    [DotNet7]
    public void can_use_list_patterns_with_condition()
    {
        Assert.That(SelfOrMessageWithCondition(new int[] { 0, 4, 3 }), Is.EqualTo("YEAH_3"));
        Assert.That(SelfOrMessageWithCondition(new int[] { 6, 4, 3 }), Is.EqualTo("error!"));
        Assert.That(SelfOrMessageWithCondition(new int[] { 1, 2, 3 }), Is.EqualTo("error!"));
        Assert.That(SelfOrMessageWithCondition(new int[] { 1, 6, 2, 3 }), Is.EqualTo("error!"));
        Assert.That(SelfOrMessageWithCondition(new int[] { 6, 3, 8, 4 }), Is.EqualTo("error!"));
    }
    

    To read more about List patterns, just head to the official documentation 🔗.

    This article first appeared on Code4IT 🐧

    Wrapping up

    This is a new feature in C#. Have you ever used it in your production code?

    Or is it “just” a nice functionality that nobody uses? Drop a message below if you have a real use if it 📩

    I hope you enjoyed this article! Let’s keep in touch on Twitter or on LinkedIn, if you want! 🤜🤛

    Happy coding!

    🐧





    Source link