C# From singular to Plural form (english)


Some collegues of mine came up with nice-to-have string extension method yesterday – ToPlural – that adds the addition ‘s’ in Plural form of english Word. This means that you can have any singular form english word, supply the count (from a data source) and the string extension method will return you the plural form of the word.

Add the following to the string extension class

   
    public static class MyExtensions
    {
        public static string ToPlural(this string input, int count = 0)
        {
            var cult = new CultureInfo("en-US");
            if (count == 1)
                return input ;

            var plu = PluralizationService.CreateService(cult)
                                  .Pluralize(input);
            return plu;
        }
    }

The following are the actual tests to make proof of concept for string extension method.

    [TestMethod]
    public void TestPluralis()
    {
            Assert.AreEqual("cars", "car".ToPlural(0));
            Assert.AreEqual("car", "car".ToPlural(1));
            Assert.AreEqual("cars", "car".ToPlural(2));
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s