c# not in the list or array

i try to show label1.Text = "Exist" if value TextBox1.Text within 1-5 and label2.Text ="Not Exist" if value not within 1-5.

private static List<int> list = new List<int>();

for (int i = 1; i < 6; i++)
            {
                list.Add(i);
            }
...
LVL 1
doramail05Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AshokSr. Software EngineerCommented:
int iValue = null;
try
{
  iValue = Convert.ToInt32(TextBox1.Text.Trim());
}
catch
{
  MessageBox.Show("Please enter a valid number!");
  return;
}
bool exists = list.Exists(element => element == iValue);
if (exists)
  label1.Text = "Exist";
else
  label1.Text = "Not Exist";

HTH
Ashok

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
_Katka_Commented:
Hi, another solution is <see code>

regard,
Kate
Int32 value;

if (Int32.TryParse(TextBox1.Text, out value))
{
    if (value >= 1 && value <= 5)
    {
        label1.Text = "Exist";
    }
    else
    {
        label1.Text = "Not Exist";
    }
}
else
{
    MessageBox.Show("Please enter a valid number!");
}

Open in new window

0
_Katka_Commented:
Or in shorter notation <see code>

regards,
Kate
Int32 value;

if (Int32.TryParse(TextBox1.Text, out value))
{
    label1.Text = (value >= 1 && value <= 5) ? "Exist" : "Not Exist";
}
else
{
    MessageBox.Show("Please enter a valid number!");
}

Open in new window

0
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

lazyberezovskyCommented:
You can use more object-oriented way - create Range class.
And use it:

int value;
if (Int32.TryParse(TextBox1.Text, out value))
{
   Range r1 = new Range(1,5);
   label1.Text = r1.IsInRange(value) ? "Exist" : "Not Exist";
}
public class Range
{
    private readonly int _upperBound;
    private readonly int _lowBound;

    public Range(int lowBound, int upperBound)
    {
        if (upperBound < lowBound)
            throw new ArgumentException("Upper bound could not be less then low bound.");

        _lowBound = lowBound;
        _upperBound = upperBound;
    }

    public int LowBound
    {
        get { return _lowBound; }
    }

    public int UpperBound
    {
        get { return _upperBound; }
    }

    public bool IsInRange(int value)
    {
        return (_lowBound <= value) && (value <= _upperBound);
    }
}

Open in new window

0
lazyberezovskyCommented:
ashok111, doramail05
int iValue = null;
What the language are you programming on??
Katka's solution better.
0
_Katka_Commented:
lazyberezovsky:

Thanks, yours is fine as well. Even better when arbitrary range is considered. doramail05 will finds out soon, it's not buildable. Also throwing exception to achieve a standard functionality is considered an anti-pattern (http://en.wikipedia.org/wiki/Anti-pattern):

http://en.wikipedia.org/wiki/Expection_handling

Note: Just to warn you ahead doramail05. It's better to start off on the right foot. Also <see attached code> for some # tips.

regards,
Kate
private void button1_Click(object sender, EventArgs e)
{
    Boolean isContainedInList;

    // #1 - try avoid the static lists when not needed (I presume that you've used it just for this example)
    if (TryGetValueExistInList(TextBox1.Text, list, out isContainedInList))
    {
        label1.Text = isContainedInList ? "Exist" : "Not Exist";
    }
    else // #2 - always try to inform the user (or somebody) what went wrong (pattern)
    {
        String message = string.Format("Value '{0} is not a valid number!", textBox1.Text);
        MessageBox.Show(message);
    }
}

// #3 - try to segment your code into logic methods (or classes see lazyberezovsky's solution) for a better readability and maintenance
Boolean TryGetValueExistInList(String textValue, List<Int32> list, out Boolean isContainedInList)
{
    // #4 - always check if all the conditions for method are satisfied first, otherwise throw an exception (pattern)
    if (list == null)
    {
        // #5 - make the exceptions as verbose as possible it will pay off (good habbit)
        // #6 - move string constants into the resources (optional)
        throw new ArgumentNullException("The list cannot be null!");
    }

    Boolean result;
    Int32 value;

    // #7 - use standard language options first (TryXXX pattern), avoid using the anti-patterns (logic)
    if (Int32.TryParse(textValue, out value))
    {
        isContainedInList = list.Exists(listValue => listValue == value);
        result = true;
    }
    else // #8 - always rather specify what is going to happen in other case, avoid variable initialization (readability, but optional)
    {
        isContainedInList = false;
        result = false;
    }

    return result;
}

Open in new window

0
lazyberezovskyCommented:
_Katka_ thanks :)
Completely agree with you about exception handling anti-pattern.
0
AshokSr. Software EngineerCommented:
lazyberezovsky,

Thanks for pointing out my error.
You cannot assign null to int.

correct would be

int iValue = 0;  // default

null can be assigned to string, etc.

Ashok
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.