Save a list after leaving the foreach loop - c#

So i am new to c# and i want to keep my list after leaving a loop....
foreach (object itemChecked1 in clVorfahr.CheckedItems)
{
List<object> VorfahrCK = clVorfahr.CheckedItems.OfType<object>().ToList();
}
foreach (object itemChecked in clNachfolg.CheckedItems)
{
List<object> NachfolgCK = clNachfolg.CheckedItems.OfType<object>().ToList();
}
After leaving this foreach loop my list is empty but when i debug and stop for each loop my list is getting data but after leaveing its completely empty

Your problem consists of two parts:
You´re creating an entire new list on every iteration of clVorfahr.CkeckedItems.
you don´t assign that list to anything, thus you can´t do anything with the list(s) when iteration was done.
So you should create the list outside the loop and fill it within:
List<object> VorfahrCK = new List<object>();
foreach (object itemChecked1 in clVorfahr.CheckedItems)
{
VorfahrCK.Add(itemChecked);
}
The following is a bit shorter but does the same:
List<object> VorfahrCK = clVorfahr.CheckedItems.OfType<object>().ToList();

Your code is confused
1, scope defined your variable in the loop so thats the place it exists, to make it exist outside the loop declare it before - do the loop and then you can use it after.
2, in your loop for each item you do exactly the same not add an item to the list..
you would have gotten away with just the line
List<object> NachfolgCK = clNachfolg.CheckedItems.OfType<object>().ToList();

Initialise them outside of the loop, otherwise they are not in the scope that you require!
List<object> VorfahrCK = new List<object>();
List<object> NachfolgCK = new List<object>();
foreach (object itemChecked1 in clVorfahr.CheckedItems)
{
VorfahrCK = clVorfahr.CheckedItems.OfType<object>().ToList();
}
foreach (object itemChecked in clNachfolg.CheckedItems)
{
NachfolgCK = clNachfolg.CheckedItems.OfType<object>().ToList();
}

You declare those variables inside foreach brackets. Therefore, they are scoped in the 2 brackets.
Declare them outside like below:
List<object> VorfahrCK = new List<object>();
foreach (object itemChecked1 in clVorfahr.CheckedItems)
{
VorfahrCK = clVorfahr.CheckedItems.OfType<object>().ToList();
}
But I don't see you use itemChecked1 anyway, why foreach?
Anyway, I usually use stuff like these:
List<string> stringList = new List<string>();
foreach (var line in anotherStringList)
{
stringList.Add(line);
}

Related

Populating a two dimensional array is adding a new element instead of a row

I have a large tab delimited text file that I need to parse.
This is a sample of the data as it looks in notepad++:
Here is my code:
private IEnumerable<string> ParsePriceFile()
{
var priceFile = Path.Combine(Settings.Default.WatchDirectory, Settings.Default.CustomerPricingDataFile);
var priceFileList = new List<string>();
foreach (var line in File.ReadLines(priceFile))
{
priceFileList.AddRange(line.Split('\t'));
}
return priceFileList;
}
I'm ending up with these results though:
I can just count each element and reference it with the appropriate index but I thought I could make a 2d array. What am I doing wrong?
You can use new List<string[]>() and then add each entire array to it:
var priceFileList = new List<string[]>();
foreach (var line in File.ReadLines(priceFile))
{
priceFileList.Add(line.Split('\t'));
}
The result is not literally a 2D array, but a List of 1D arrays instead. For many purposes this will not make much difference.
You are using AddRange on a List, which simply adds the IEnumerable passed in to the end of the list. If you want two values for each item, you'll have to make your List something that will hold that, like a Dictionary<string, string> or a List<<Tuple<string, string>
var priceFileList = new Dictionary<string, string>();
foreach (var line in File.ReadLines(priceFile))
{
priceFileList.Add(line.Split('\t')[0], line.Split('\t')[1]);
}

Iterating through list of values in a dictionary c#

I have a dictionary defined as below ,
Dictionary<string, List<string>> dictionaryValues = new Dictionary<string, List<string>>();
Since I have a List of values I want iterate through them and find out what values have ="true" in them
Here is the source code what I have tried thus far
Would appreciate any help on this
List<string> listValues = new List<string>();
listValues.Add("value=true");
listValues.Add("value=false");
dictionaryValues.Add("Name", listValues);
foreach (var item in dictionaryValues)
{
foreach (var item in item.Value)
{
if (item.Contains("true"))
{
}
}
}
You can use the Values property on the dictionary. Also, you'll have to rename one of the "item" variables in either of the foreach loops.
See also msdn here.
foreach (List<string> items in dictionaryValues.Values)
{
foreach (string item in items)
{
if (item.Contains("true"))
{
}
}
}
I've also made it explicit what types the "items" and "item" are for clarity.
By using Linq you can do this with SelectMany and Where:
var valuesWithTrue = dictionaryValues.Values.SelectMany(x => x).Where(x => x.Contains("true"));

Add elements to a list while iterating over it

I'm trying to add new elements to a list of lists while iterating over it
List<List<String>> sets = new List<List<string>>();
foreach (List<String> list in sets)
{
foreach (String c in X)
{
List<String> newSet = ir_a(list, c, productions);
if (newSet.Count > 0)
{
sets.Add(newSet);
}
}
}
The error I get after a few loops is this:
Collection was modified; enumeration operation may not execute
I know the error is caused by modifying the list, so my question is: What's the best or most fancy way to sort this thing out?
Thanks
You might get away with this in other languages but not C#. They do this to avoid funny runtime behaviour that isn't obvious. I prefer to set up a new list of things you are going to add, populate it, and then insert it after the loop.
public class IntDoubler
{
List<int> ints;
public void DoubleUp()
{
//list to store elements to be added
List<int> inserts = new List<int>();
//foreach int, add one twice as large
foreach (var insert in ints)
{
inserts.Add(insert*2);
}
//attach the new list to the end of the old one
ints.AddRange(inserts);
}
}
Imagine that if you had a foreach loop, and you added an element to it each time, then it would never end!
Hope this helps.

Accessing objects inside List<T> by adding them using AddRange

Is there a way to access the objects in the list? like, getting an exact field in a particular object. For Instance:
List<Object> allObjectResult = new List<Object>();
allObjectResult.AddRange(method(ObjectOne.ToArray()));
allObjectResult.AddRange(method(ObjectTwo.ToArray()));
allObjectResult.AddRange(method(ObjectThree.ToArray()));
I want to get a particular field in ObjectOne, ObjectTwo and ObjectThree. How am I able to do that?
Updated Question
In List we can access elements position by order. My first attempt in getting the a particular value in an object inside a List works. This is what I did:
Create a new instance of a list:
List<Object> objList = new List<Object>();
Added data on it:
objList.Add(objdata);
Use it in a method:
Object[] result = binding.method(Object.ToArray());
Loop through:
for(i = 0; i < result.Length; i++)
{
Console.WriteLine("objs {0} - {1}", objList[i].Name, result[i].id);
}
However, What I want is I have three objects. What I did is added them in a List:
List<Object> allObjectResult = new List<Object>();
allObjectResult.AddRange(binding.method(ObjectOneList.ToArray()));
allObjectResult.AddRange(binding.method(ObjectTwoList.ToArray()));
allObjectResult.AddRange(binding.method(ObjectThreeList.ToArray()));
I want to do the same thing like what I did in getting a name in an object (anyway, it's an object within a List). I want them to access using a loop.
Select objects of a certain type:
foreach (var obj1 in allObjectResult.OfType<ObjectOne>()) {
Console.WriteLine(obj1.Whatever);
}
Check the type dynamically:
foreach (var obj in allObjectResult) {
if (obj is ObjectOne) {
var obj1 = (ObjectOne)obj;
Console.WriteLine(obj1.Whatever);
} // else ...
}

HashSet Iterating While Removing Items in C#

I have a hashset in C# that I'm removing from if a condition is met while iterating though the hashset and cannot do this using a foreach loop as below.
foreach (String hashVal in hashset)
{
if (hashVal == "somestring")
{
hash.Remove("somestring");
}
}
So, how can I remove elements while iterating?
Use the RemoveWhere method of HashSet instead:
hashset.RemoveWhere(s => s == "somestring");
You specify a condition/predicate as the parameter to the method. Any item in the hashset that matches the predicate will be removed.
This avoids the problem of modifying the hashset whilst it is being iterated over.
In response to your comment:
's' represents the current item being evaluated from within the hashset.
The above code is equivalent to:
hashset.RemoveWhere(delegate(string s) {return s == "somestring";});
or:
hashset.RemoveWhere(ShouldRemove);
public bool ShouldRemove(string s)
{
return s == "somestring";
}
EDIT:
Something has just occurred to me: since HashSet is a set that contains no duplicate values, just calling hashset.Remove("somestring") will suffice. There is no need to do it in a loop as there will never be more than a single match.
You can't remove items from a collection while looping over it with an enumerator. Two approaches to solve this are:
Loop backwards over the collection using a regular indexed for-loop (which I believe is not an option in the case of a HashSet)
Loop over the collection, add items to be removed to another collection, then loop over the "to-be-deleted"-collection and remove the items:
Example of the second approach:
HashSet<string> hashSet = new HashSet<string>();
hashSet.Add("one");
hashSet.Add("two");
List<string> itemsToRemove = new List<string>();
foreach (var item in hashSet)
{
if (item == "one")
{
itemsToRemove.Add(item);
}
}
foreach (var item in itemsToRemove)
{
hashSet.Remove(item);
}
I would avoid using two foreach loop - one foreach loop is enough:
HashSet<string> anotherHashSet = new HashSet<string>();
foreach (var item in hashSet)
{
if (!shouldBeRemoved)
{
anotherSet.Add(item);
}
}
hashSet = anotherHashSet;
For people who are looking for a way to process elements in a HashSet while removing them, I did it the following way
var set = new HashSet<int> {1, 2, 3};
while (set.Count > 0)
{
var element = set.FirstOrDefault();
Process(element);
set.Remove(element);
}
there is a much simpler solution here.
var mySet = new HashSet<string>();
foreach(var val in mySet.ToArray() {
Console.WriteLine(val);
mySet.Remove(val);
}
.ToArray() already creates a copy for you. you can loop to your hearts content.
Usually when I want to iterate over something and remove values I use:
For (index = last to first)
If(ShouldRemove(index)) Then
Remove(index)

Categories