How to add a collection of list into a list? - c#

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.

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

Distinct items in List

I have an excel spreadsheet that I am trying to populate a list with only unique values. I have found LinqToExcel which I would prefer not to use. At most there will be 2000 rows which isn't very much.
My thought was:
List<string> lst = new List<string>();
string item;
for (i=2; i<2001; i++)
{
item = ws.cells[i,3];
if(lst.**notInList**(item))
{
lst.Add(item);
}
}
I know that there isn't notInList(), but I was hoping for something similar or another idea.
var values = Enumerable.Range(2, 1999)
.Select(i => ws.cells[i,3])
.Distinct()
.ToList();
Use Contains instead
List<string> lst = new List<string>();
string item;
for (i=2; i<2001; i++)
{
item = ws.cells[i,3];
if(!lst.Contains(item))
{
lst.Add(item);
}
}
List<string> lst = new List<string>();
string item;
for (i=2; i<2001; i++)
{
item = ws.cells[i,3];
if(!lst.Contains(item))
{
lst.Add(item);
}
}
If you want the items filtered for identical entries, you could use the .Distinct method from linq.
var distinctList = lst.Distinct();
There's also List.Contains(item)
If you know from the get-go that this collection should contain only unique elements, also consider using a HashSet<T> instead.

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

Creating a List<string> containing a single string N times

Is there any way to construct a list of type List<string> which contains a single string N times without using a loop? Something similar to String(char c, int count) but instead for List of strings.
List<string> list = new List<string>() { "str", "str", "str", ..... N times };
You can use Repeat():
List<String> l = Enumerable.Repeat<String>("foo", 100).ToList<String>();
It will still use a loop of course, but now you don't "see" it.
Try doing this:
List<String> list = new List<String>();
for(int i=0; i<N; i++)
{
list.add("str");
}

Foreach and modification to iteration variable

What's the proper way to do this?
foreach(Object obj in ObjectList<Object>)
{
Object changedObject= GetInfo(obj);
obj=changedObject; //no good
obj.prop1 = changedObject.prop1; //ok?
obj.prop2 = changedObject.prop2; //ok?
better way?
}
Use a for loop instead:
for (int i = 0; i < list.Count; i++)
{
Object changedObject = GetInfo(list[i]);
list[i] = changedObject;
}
You could also use LINQ, and append .ToList() if you need a list instead of an IEnumerable<T>:
var query = result.Select(o => GetInfo(o));
I think you're better off creating a new list of objects, ie:
var newList = new List<Object>();
foreach(Object obj in ObjectList<Object>)
{
newList.Add(GetInfo(obj));
}
Then either replace ObjectList with newList or just return it from whatever you're doing

Categories