Implement new LINQ to objects: 6-repeat by yourself

Source: Internet
Author: User

Translated fromJon SkeetSeries of blog posts"Edulinq".

Original article address:


The topic of this article is irrelevant,Repeat. AboutRepeat.EmptyLess. Write this blog to ensure the integrity of this series.

RepeatWhat is it?

RepeatIt is a static generic method, not an extension method. It has only one signature form:

Public StaticIenumerable <tresult> repeat <tresult> (

Tresult element,


It returns a sequence that contains"Count,.RepeatOnly one parameter verification is required: Check"Count"Is not a negative number.

What should we test?

There are not many things to test. I only want to use four scenarios:

LA simple test repeats a string three times

LAn empty sequence (repeat one element0Times)

LMultiple containNullSequence (just to prove"Element"Can beNull)

LUse a negative number asCountTo prove that the parameter verification will be executed and is executed immediately.

I am afraid these points are not very popular.

To implement it!

The only thing we may do wrong during implementation is to verify the parameters.CodeIt is written together with the iterator code block. However, we have already done "Split implementation" for many times, so we will certainly not make this mistake. The following code is not good enough.RepeatThe methods are all:

Public StaticIenumerable <tresult> repeat <tresult> (tresult element,IntCount)


If(Count <0)


ThrowNewArgumentoutofrangeexception ("Count");


ReturnRepeatimpl (element, count );


Private StaticIenumerable <tresult> repeatimpl <tresult> (tresult element,IntCount)


for ( int I = 0 ; I





This is all about today. It is worth noting that...There is nothing worth noting.


In fact, there is no conclusion to write. Next time we will talk aboutCountAndLongcountThere are some interesting things to elaborate on. 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.