Validating culture name using LINQ
Imagine that we have some class (e.g. UserProfile) with Culture property for storing a culture specific string, in other words a culture name.
class UserProfile { private string _culture; public string Culture { get { return _culture; } set { _culture = value; } } }
Our goal is to allow only existing culture name to be set and avoid an invalid one. Let’s start by writing unit tests where we will try to assign valid and invalid values to our property (using MSTest):
[TestMethod] public void UserProfile__Set_Culture() { UserProfile userProfileTest = new UserProfile(); userProfileTest.Culture = "en-US"; Assert.AreEqual("en-US", userProfileTest.Culture); } [TestMethod] public void UserProfile__Set_InvalidCulture__ShouldFail() { UserProfile userProfileTest = new UserProfile(); userProfileTest.Culture = "american"; Assert.IsNull(userProfileTest.Culture); }
The default property behavior is just setting and getting some private field (_culture) and therefore the second test would fail if we run it because _culture property wouldn’t be null. Now we need some simple control mechanism to validate our string. As the heading says I am going to use LINQ (Language Integrated Query) to do so.
public string Culture
{
get { return _culture; }
set
{
CultureInfo[] cultures = System.Globalization.CultureInfo.GetCultures
(CultureTypes.SpecificCultures);
var selectCulture = from p in cultures
where p.Name == value
select p;
if (selectCulture.Count() == 1)
{
_culture = value;
}
}
}
The first step is to get all existing cultures into an array and then simply query it with our input. If an existing query is found property will be correctly assigned and both of our tests will pass.