Search code examples
c#asp.netarraylistactive-directorydirectorysearcher

How I get a Arraylist with not double values?


I want do get a Departmentlist from the Active Directory for this I use the Directoryentry and the DirectorySearcher class. I get the list of departments but how I can delete the double values in this list.

for example my list now:

it
it
it
vg
per
vg
...

And I want only one of this values in the list how this:

it
vg
per
...(other departments)

I want to use this list for a dropDownlist list.

my Code:

public static void GetAllDepartments(string domaincontroller) 
        {
            ArrayList list = new ArrayList();

            int Counter = 0;

            string filter = "(&(objectClass=user)(objectCategory=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(sn=*)(|(telephoneNumber=*)(mail=*))(cn=*)(l=*))";

            List<User> result = new List<User>();

            DirectoryEntry Entry = new DirectoryEntry(domaincontroller);

            DirectorySearcher Searcher = new DirectorySearcher(Entry, filter);

            foreach (SearchResult usr in Searcher.FindAll())
            {
                result.Add(new User()
                {
                    department = GetLdapProperty(usr, "Department")

                });

                Counter++;
            }

            for (int i = 0; i < Counter; i++)
            {

                list.Add(result[i].department);

            }
        }

How I can show only one value in the Arraylist?


Solution

  • You can also use the Exists clause to see if the element already exists in the list.

    using System.Linq;
    
    for (int i = 0; i < Counter; i++)
    {
       bool deptExists = list.Exists(ele => ele == result[i].department);
    
       if(!deptExists){
        list.Add(result[i].department);
       }
    }