How I get a Arraylist with not double values? - c#

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?

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

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

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

Related

how to create a loop that creates lists

I want to create a loop that makes lists the name of the lists that need to come from another list.
I tried doing it like that.
for (int i = 0; i < Names.Count; i++)
{
List<string> Name[i] = new List<string>();
}
Just pass the source collection in the list constructor, like this
var newList = new List<string>(Names);
If you want more control, you can still do your loop, but declare the destination list first:
var newList = new List<string>();
for (int i = 0; i < Names.Count; i++)
{
newList.Add(Names[i]);
}
And finally, if you need a list of lists, where each list is named, you'd use a different data structure, for example a Dictionary<string, List<string>> instead:
var listOfLists = new Dictionary<string, List<string>>();
for (int i = 0; i < Names.Count; i++)
{
listOfLists.Add(
Names[i], // <--- the name of the list is the key
new() // <--- the named list (initially empty)
);
}
Which, in modern C#, can be shortened further to become
var listOfLists = Names.ToDictionary(name => name, _ => new List<string>());

How to name an array based on a variable name

Working is:
foreach (string feature in alpha)
{
for (int i=0; i < l.Count; i++)
{
if (l[i] == feature)
{
string[] ("{0}",feature) = new string[];
}
}
}
string[] ("{0}",feature) = new string[]; is incorrect. What needs to be done is, whenever there is a match for the condition (l[i] == feature) , create a new string array as: string[] (whatever string there is in feature) = new string[].
Possible?
I think a dictionary is what you want.
var arrays = alpha
.Where(a => l.Contains(a))
.ToDictionary(a => a, a => new List<string>());
Then to access one:
List<string> array = arrays["somefeature"];
Also stop using arrays, there's almost no good reason to choose them over the other collection types. I have used List because you said you want to append to it.
You could use a sorted list where the key value would be your feature;
var featureList = new SortedList<string, string[]>();
foreach (string feature in alpha)
{
var matchingFeatures = new List<string>();
for (int i = 0; i < l.Length; i++)
{
if (l[i] == feature)
{
matchingFeatures.Add(l[i]);
}
}
featureList.Add(feature, matchingFeatures.ToArray());
}

How to iterate through IEnumerable collection using for each or foreach?

I want to add one by one values but in for loop how can I iterate
through one by one values and add it inside dictionary.
IEnumerable<Customer> items = new Customer[]
{
new Customer { Name = "test1", Id = 111},
new Customer { Name = "test2", Id = 222}
};
I want to add { Name = "test1", Id = 111} when i=0
and want to add { Name = "test2", Id = 222} when i=1 n so on..
Right now i'm adding full collection in every key.(want to achieve this using foreach or forloop)
public async void Set(IEnumerable collection)
{
RedisDictionary<object,IEnumerable <T>> dictionary = new RedisDictionary>(Settings, typeof(T).Name);
// Add collection to dictionary;
for (int i = 0; i < collection.Count(); i++)
{
await dictionary.Set(new[] { new KeyValuePair<object,IEnumerable <T> ( i ,collection) });
}
}
If the count is need and the IEnumerable is to be maintained, then you can try this:
int count = 0;
var enumeratedCollection = collection.GetEnumerator();
while(enumeratedCollection.MoveNext())
{
count++;
await dictionary.Set(new[] { new KeyValuePair<object,T>( count,enumeratedCollection.Current) });
}
New version
var dictionary = items.Zip(Enumerable.Range(1, int.MaxValue - 1), (o, i) => new { Index = i, Customer = (object)o });
By the way, dictionary is a bad name for some variable.
I'm done using
string propertyName = "Id";
Type type = typeof(T);
var prop = type.GetProperty(propertyName);
foreach (var item in collection)
{
await dictionary.Set(new[] { new KeyValuePair<object, T>(prop.GetValue(item, null),item) });
}
So you want to a an item from the collection to the dictionary in the for loop?
If you cast your IEnumerable to a list or an array, you can easily access it via the index. For example like this:
Edit: Code at first created a list every time it looped, which should of course be avoided.
var list = collection.ToList(); //ToArray() also possible
for (int i = 0; i < list.Count(); i++)
{
dictionary.Add(i, list[i]);
}
I'm not 100% if that is what you need, though. More details to your question would be great.

How to add a collection of list into a list?

I have my code like,
List<string> list = new List<string>();
model.QuestionSetList = new List<string>();
for (int i = 0; i < response.QuestionsInfoList.Count(); i++)
{
list.Add(response.QuestionSetInfo.QuestionsInfoList[i].Question);
foreach (AnswerSetContract answerSetContract in response.QuestionsInfoList[i].AnswersInfoList)
{
list.Add(answerSetContract.AnswerText);
}
model.QuestionSetList.Add(list)
}
I cannot add a list into another list.Kindly tell me what to do in this case.
Look at the Concat function within the System.Linq namespace
I.e.
using System.Linq;
List<string> list = new List<string>();
model.QuestionSetList = new List<string>();
for (int i = 0; i < response.QuestionsInfoList.Count(); i++)
{
list.Add(response.QuestionSetInfo.QuestionsInfoList[i].Question);
foreach (AnswerSetContract answerSetContract in response.QuestionsInfoList[i].AnswersInfoList)
{
list.Add(answerSetContract.AnswerText);
}
model.QuestionSetList = model.QuestionSetList.Concat(list);
}
But why not at the place of; list.Add(answerSetContract.AnswerText); add it directly to model.QuestionSetList?
So like this;
List<string> list = new List<string>();
model.QuestionSetList = new List<string>();
for (int i = 0; i < response.QuestionsInfoList.Count(); i++)
{
list.Add(response.QuestionSetInfo.QuestionsInfoList[i].Question);
foreach (AnswerSetContract answerSetContract in response.QuestionsInfoList[i].AnswersInfoList)
{
model.QuestionSetList.Add(answerSetContract.AnswerText);
}
}
If you want a List of Lists, then your QuestionSetList would have to be:
model.QuestionSetList = new List<List<<string>>()
Consider creating a custom type though, otherwise it's a bit like inception, list in a list in a list in a list.........
Or if you're actually wanting to combine the Lists, then use Concat:
list1.Concat(list2);
You should try with AddRange, it allows to add a collection to a List
http://msdn.microsoft.com/en-us/library/z883w3dc.aspx
model.QuestionSetList is a list of strings.
You're trying to add a list of strings to it. As their types are incompatible, it won't allow you to do that.
Try making model.QuestionSetList a List<List<string>> and see if that helps you.

Add to array list from listbox selected item does not work properly

I have a program where I am trying to move items from one arrayList to another via a listbox and then print out the info in an XML, but the error I have is when I am adding it often certain times the values would repeat, when there are no repeats.
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
list1.Add(new RandomClass(var1, var2, var3, var4, var5, var6, var7));
foreach (object o in list1)
{
RandomClass m = (RandomClass)o;
selectionBox.Items.Add(m);
}
This is my initialization code.
bool req = true;
if (selectionBox.SelectedItem != null)
{
Count++;
errorLabel.Text = "";
for (int i = 0; i < selectionBox.Items.Count; i++)
{
if (selectionBox.GetSelected(i) == true)
{
RandomClass m = selectionBox.SelectedItem as RandomClass;
if (m.var2 == ((RandomClass)selectionBox.Items[i]).var2)
{
list2.Add(list1[i]);
}
}
}
}
else
{
errorLabel.Text = "Error";
}
Here is where I add to another array list. However as I said often the item would repeat and not be different, how can I resolve this problem?
Try clearing the second list each time you scan and add items from the first list.
list2.Clear();
for (int i = 0; i < selectionBox.Items.Count; i++)
....
I have fixed this problem using a list with my class, and there does not seem to be a problem.
List<RandomClass> list2 = new List<RandomClass>();
And then when adding I just simply put the following in the if statement
list2.Add(m);

Categories