Blog author:
Niladri.Biswas | Posted on: 7/8/2012 | Category:
C# Blogs | Views: 1196 | Status:
[Member] |
Points: 75
|
Alert Moderator
Suppose we have a requirement like we want to check if a particular input string matches or not
Generally we write as under
var input = "xyz";
if (input != "a")
{
Console.WriteLine("Not matched");
}
else
{
Console.WriteLine("matched");
}
output
---------
Not matched
Ok.That's fine. Now consider, we have two such condition to check, so generally we go ahead as under
var input = "xyz";
if (input != "a" && input != "b")
{
Console.WriteLine("Not matched");
}
else
{
Console.WriteLine("matched");
}
output
---------
Not matched
If there is a third condition to check , so it will be
if (input != "a" && input != "b" && input != "c")
And so on...So if there are many such conditions to check we need to write many such conditional statements inside "If" which is difficult to maintain and less readable.
An alternate and cleaner way is to put them inside an array and search if the string is present or not as under
var input = "c";
var recordCount = new string[] { "a", "b","c","d" }.Where(i => i == input).Count();
var result = (recordCount == 0) ? "Not matched":"matched";
Console.WriteLine(result);
In this method, we find that only we need to extend the array if some more requirement comes.It is readable and maintainable too.
Thanks for reading
Best Regards,
Niladri Biswas
Found interesting? Add this to: