Question

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?

Was it helpful?

Solution 3

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);
   }
}

OTHER TIPS

First of all, I recommend that instead of using an ArrayList, use a Strongly-Typed list.
Then, use the Distinct() method to only get a list of unique values (no duplicates).

For instance:

List<String> list = new List();

....

 for (int i = 0; i < Counter; i++)
 {
     list.Add(result[i].department.ToString());
 }

 var noDuplicates = list.Distinct();

Try Distinct() in System.Linq extensions :

list = list.Distinct();

Use the Enumerable.Distinct Method method.

Use a HashSet and only insert the non-duplicate values.

HashSet<string> list = new HashSet<string>();

...

for (int i = 0; i < Counter; i++)
{
   string dep = result[i].department.ToString();

   // true if dep was added, false if not. No exception at this point.
   list.Add(dep);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top