how to create a loop that creates lists - c#

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

Related

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 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.

custom sorting in a bindinglist of keyvaluepairs

I have a bindinglist of keyvaluepair filled dynamicaly.
BindingList<KeyValuePair<int, string>> Homelist = new BindingList<KeyValuePair<int, string>>();
foreach (ListItem item in listBox2.Items)
{
Homelist.Add(new KeyValuePair<int, string>(item.Id, item.Name));
}
The list has key(id) and value(text) as shown
I want to sort the first 5 items asc and then the rest items also asc.the sorting must be by value and not by key.
example: if I have the values : 4,5,8,7,6,10,9,3,2,1,22 the sorting result must be 4,5,6,7,8 ,1,2,3,9,10,22.Any idea?
solved answer:
public int Compare(KeyValuePair<int,string> a, KeyValuePair<int,string> b)
{
return a.Value.CompareTo(b.Value);
}
List<keyvaluepair><int,>> Playinglist = new List<keyvaluepair><int,>>();
for (int i = 0; i < 5; i ++)
{
Playinglist.Add(Homelist[i]);
}
Playinglist.Sort(Compare);
List<keyvaluepair><int,>> Benchlist = new List<keyvaluepair><int,>>();
for (int i = 5; i < Homelist.Count(); i++)
{
Benchlist.Add(Homelist[i]);
}
Benchlist.Sort(Compare);
//union 2 lists
var unionedList = new List<keyvaluepair><int,>>();
unionedList.AddRange(Playinglist.Union(Benchlist));
Homelist.Clear();
for (int i = 0; i < unionedList.Count(); i++)
{
Homelist.Insert(i, unionedList[i]);
}
game.GetHomelist = Homelist;
The idea that Tony Hopkinson said is to chop the list into two. Sort them separately and then join them back togther.After that clear the bindlist and filled from the join list. Sorting can be applied only in List<> and not to the BindLists<>.The answere is in edited question

Compare dictionary <string,List<string>> single value with a list of values c#

parse the xml and form dictionary with same key for multiple values
Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
doc.Load(confidencethresholdFilePath + "\\input.xml");
// XmlNodeList nodes = doc.DocumentElement.SelectNodes("/root/file");
doc.Normalize();
XmlNodeList nList = doc.GetElementsByTagName("key");
for (int temp = 0; temp < nList.Count; temp++)
{
string keyvalue = "";
XmlNode nNode = nList.Item(temp);
List<String> main = new List<string>();
ArrayList arrayList = new ArrayList(main);
XmlElement ele = (XmlElement)nNode;
keyvalue = ele.GetAttribute("value");
for (int i = 0; i < ele.ChildNodes.Count; i++)
{
if (ele.ChildNodes[i].ChildNodes.Count == 1)
{
Double sec = Double.Parse(ele.ChildNodes[i].InnerText);
int seg = TimeToSegment(sec);
Console.WriteLine("" + seg);
main.Add(Convert.ToString(seg));
}
}
dictionary.Add(keyvalue, main);
}
I want to comapare with single value but it shows error
dictionary.ContainsValue(s.sname) invalid arguments
I am not sure what you want to check but if you are trying to match keys then do this:
dictionary.ContainsKey(s.sname);
Or you might try:
IEnumerable<KeyValuePair<string,List<string>>> ienKeyVals = dictionary.Where(x => x.Value.Contains(s.sname));
parse the xml and form dictionary with same key for multiple values
A dictionary cannot contain duplicate keys. Its not possible to add duplicate items to a Dictionary - an alternative is to use the Lookup class.
Enumerable.ToLookup Method
Creates a generic Lookup from an IEnumerable.

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

Categories