115

Is there any algorithm in c# to singularize - pluralize a word (in english) or does exist a .net library to do this (may be also in different languages)?

0

11 Answers 11

195

You also have the System.Data.Entity.Design.PluralizationServices.PluralizationService.

UPDATE: Old answer deserves update. There's now also Humanizer: https://github.com/MehdiK/Humanizer

6
  • 2
    Hmmm are you allow to redistribute, or just use, a Design DLL? I ask that because I know that the license for DevExpress prohibit redistributing any .design DLL. Commented Mar 30, 2011 at 19:39
  • 64
    Opening the code with ILSpy shows a class called EnglishPluralizationService, which has lots of exceptional cases defined in and makes for interesting reading. I particularly like 'pneumonoultramicroscopicsilicovolcanoconiosis', which I find myself using all the time in my entity models... 8o)
    – MrKWatkins
    Commented Jan 19, 2012 at 17:41
  • 8
    I can guess how that got added. A tester filed a bug on the dev saying it does not work for the said word. Dev fixed it. Both shared a laugh. Commented Mar 30, 2013 at 15:43
  • 2
    @MrKWatkins Sounds more like 'supercalifragilisticexpialidocious' Commented Apr 1, 2015 at 11:58
  • 1
    Humanizer is a great recommendation. I'd of course implemented like 15% of it myself before finding out it existed.
    – Casey
    Commented May 6, 2015 at 14:44
20

I can do it for Esperanto, with no special cases!

string plural(string noun) { return noun + "j"; }

For English, it would be useful to become familiar with the rules for Regular Plurals of Nouns, as well as Irregular Plurals of Nouns. There is a whole Wikipedia article on the English plural, which may have some helpful information too.

2
  • 6
    You should make it throw if you pass in a verb or adverb!
    – Timwi
    Commented Sep 17, 2010 at 3:25
  • 1
    @Matt: Of course this is appropriate for the nominative case; I trust that extending this method to the accusative case is straightforward for an astute reader. Commented Jul 27, 2012 at 2:36
14

Most ORMs have a stab at it, although they generally aren't perfect. I know Castle has it's Inflector Class you can probably poke around. Doing it "perfectly" isn't an easy task though (English "rules" aren't really rules :)), so it depends if you are happy with a "reasonable guess" approach.

2
  • From your suggestion I searched for "Inflector" and found this andrewpeters.net/inflectornet that sould basically be the same of the Castle one
    – Ronnie
    Commented Jan 24, 2009 at 8:02
  • 4
    Actually its not basically the same, its identical. Commented Feb 17, 2010 at 18:40
12

I cheated in Java - I wanted to be able to produce a correct string for "There were n something(s)", so I wrote the foll. little overloaded utility method:

static public String pluralize(int val, String sng) {
    return pluralize(val,sng,(sng+"s"));
    }

static public String pluralize(int val, String sng, String plu) {
    return (val+" "+(val==1 ? sng : plu)); 
    }

invoked like so

System.out.println("There were "+pluralize(count,"something"));
System.out.println("You have broken "+pluralize(count,"knife","knives"));
9
  • This only covers a small sections of grammar though, it doesn't account for words like quizzes, parties, halves, mice, indices, etc. It's a good first stab, but there are a lot of other rules that should probably be processed first.
    – Jeremy S
    Commented Jan 12, 2010 at 19:23
  • 4
    @Jeremy: Why not?: println("You have passed " + singularPlural(count,"quiz","quizzes") + " so far") Commented Jan 27, 2010 at 2:22
  • I might be interpreting the question differently. I'm thinking the algorithm should be determining the plural form without any hint from the developer, while your method puts the onus of knowing what the plural form is on the developer.
    – Jeremy S
    Commented Jan 27, 2010 at 17:09
  • 3
    @Jeremy: Hence the "I cheated..." lead in - doesn't seem to warrant a downvote. Commented Sep 17, 2010 at 4:34
  • 1
    Agreed. I also think the information provided was useful, which is why any downvote didn't come from me. I don't downvote in general, along the lines of the "one man's junk...".
    – Jeremy S
    Commented Oct 20, 2010 at 16:29
10

I've created a tiny library for this in .net (C#), called Pluralizer (unsurprisingly).

It's meant to work with full sentences, something like String.Format does.

It basically works like this:

var target = new Pluralizer();
var str = "There {is} {_} {person}.";

var single = target.Pluralize(str, 1);
Assert.AreEqual("There is 1 person.", single);

// Or use the singleton if you're feeling dirty:
var several = Pluralizer.Instance.Pluralize(str, 47);
Assert.AreEqual("There are 47 people.", several);

It can also do way more than that. Read more about it on my blog. It's also available in NuGet.

3
  • Any advantage over System.Data.Entity.Design.PluralizationServices.PluralizationService? Commented Mar 4, 2011 at 1:58
  • 4
    Yup, that library only does single words, and only nouns (although Pluralizer uses that class internally). This library makes to make whole sentences easier to write. Have a look at my blog for more examples. Pluralizer.Instance.Pluralize("{She} {is} going to {her|their respective} {home}.", 5) Commented Mar 4, 2011 at 2:28
  • Shaun Wilson - My computer is currently in parts. I'm rushing to get it back up and will update within a day or two. In the mean time, nuget.org/packages?q=pluralizer Commented Jan 30, 2013 at 22:34
8

I whipped one together based on the Rails pluralizer. You can see my blog post here, or on github here

output = Formatting.Pluralization(100, "sausage"); 
2
  • 3
    Thanks for sharing. Glad I didn't need to reference another assembly. Commented Sep 29, 2014 at 12:34
  • 1
    Simple and beautiful!, but it misses the Singularize functionality
    – amd
    Commented May 5, 2017 at 8:59
5

As the question was for C#, here is a nice variation on Software Monkey's solution (again a bit of a "cheat", but for me really the most practical and reusable way of doing this):

    public static string Pluralize(this string singularForm, int howMany)
    {
        return singularForm.Pluralize(howMany, singularForm + "s");
    }

    public static string Pluralize(this string singularForm, int howMany, string pluralForm)
    {
        return howMany == 1 ? singularForm : pluralForm;
    }

The usage is as follows:

"Item".Pluralize(1) = "Item"
"Item".Pluralize(2) = "Items"

"Person".Pluralize(1, "People") = "Person"
"Person".Pluralize(2, "People") = "People"
4

Subsonic 3 has an Inflector class which impressed me by turning Person into People. I peeked at the source and found it naturally cheats a little with a hardcoded list but that's really the only way of doing it in English and how humans do it - we remember the singular and plural of each word and don't just apply a rule. As there's not masculine/feminine(/neutral) to add to the mix it's a lot simpler.

Here's a snippet:

AddSingularRule("^(ox)en", "$1");
AddSingularRule("(vert|ind)ices$", "$1ex");
AddSingularRule("(matr)ices$", "$1ix");
AddSingularRule("(quiz)zes$", "$1");

AddIrregularRule("person", "people");
AddIrregularRule("man", "men");
AddIrregularRule("child", "children");
AddIrregularRule("sex", "sexes");
AddIrregularRule("tax", "taxes");
AddIrregularRule("move", "moves");

AddUnknownCountRule("equipment");

It accounts for some words not having plural equivalents, like the equipment example. As you can probably tell it does a simple Regex replace using $1.

Update:
It appears Subsonic's Inflector is infact the Castle ActiveRecord Inflector class!

3

Not much documentation from MSDN on the specific usage of the PluralizationService class so here is a unit test class (NUnit) to show basic usage. Notice the odd test case at the bottom that shows the service isn't perfect when it comes to non-standard plural forms.

[TestFixture]
public class PluralizationServiceTests
{
    [Test]
    public void Test01()
    {
        var service = PluralizationService.CreateService(CultureInfo.CurrentCulture);

        Assert.AreEqual("tigers", service.Pluralize("tiger"));
        Assert.AreEqual("processes", service.Pluralize("process"));
        Assert.AreEqual("fungi", service.Pluralize("fungus"));

        Assert.AreNotEqual("syllabi", service.Pluralize("syllabus")); // wrong pluralization
    }
}
2

Using Microsoft's Northwind example database:

 System.Data.Entity.Design.PluralizationServices.PluralizationService.CreateService(new System.Globalization.CultureInfo("en-US"));

Singularize does not Singularize "Order_Details" It returns "Order_Details" with the s at the end. What is the work around?

2
  • 2
    This is a question, not an answer to a question... but Pluralize() and Singularize() only work with dictionary words. There's a way to add words using ICustomPluralizationMapping.AddWord, but at least for me that wasn't a very good solution when you may have lots of not-real words like code names.
    – tordal
    Commented Feb 19, 2015 at 18:22
  • @tordal Thank you, this is exactly what I came to this question for
    – Chad
    Commented Nov 27, 2019 at 23:41
1

You can use PluralizationService of System.Data.Entity (.NET Framework 4.0), as shown in this page: http://zquanghoangz.blogspot.it/2012/02/beginner-with-pluralizationservices.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.