Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList Element Comparison

I have a ArrayList with five Numbers, for an example 1,2,3,4,5. Same number can not be repeated. How can I check it?

like image 759
chamara Avatar asked Jul 28 '26 09:07

chamara


2 Answers

You can do Arraylist.Contains() method to check whether an item exists in the Arraylist.

private void AddItems(object o)
{
if(!Arraylist1.Contains(o))
{
Arraylist1.Add(o);
}
}

http://msdn.microsoft.com/en-us/library/system.collections.arraylist.contains(v=VS.100).aspx

like image 104
Anuraj Avatar answered Aug 01 '26 23:08

Anuraj


Another way using linq:

        ArrayList list = new ArrayList { 1, 9, 2, 1, 6, 5 };

        var x = from l in list.OfType<int>()
                group l by l into g
                where g.Count() > 1
                select g.Key;

        if (x.Count() > 0)
        {
           // Duplicate found
        }
like image 44
Mitch Wheat Avatar answered Aug 01 '26 22:08

Mitch Wheat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!