Iterating through list of values in a dictionary c# - 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"));

Related

Save a list after leaving the foreach loop

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

Compare values in Dictionary with Another List Items

I have a problem here. I have implemented a dictionary MASTERDATALIST and a list DEPARTMENTLIST containing s specific set of items.
What I need is to compare the values of each key in MASTERDATALIST with the items of DEPARTMENTLIST.
If they are not equal, then that key should be added to another list "FAILEDLIST"
Any help would be appreciated.
Thanks!
I'm assuming that what you mean by If they are not equal is If the key is not found in the list.
What you need to do is:
loop through the items in MasterDataList
loop through the values for each item in the dictionary
check if DepartmentList contains this item
if not, add the item to FailedList
MasterDataList.Add("key1", new List<string>() { "list1_item1", "list1_item2" });
MasterDataList.Add("key2", new List<string>() { "list2_item1", "list2_item2" });
MasterDataList.Add("key3", new List<string>() { "list3_item1", "list3_item2" });
DepartmentList.Add("list1_item1");
DepartmentList.Add("list1_item2");
DepartmentList.Add("list2_item1");
DepartmentList.Add("list2_item2");
foreach (KeyValuePair<string, List<string>> item in MasterDataList)
{
foreach (var listItem in item.Value)
{
if (!DepartmentList.Contains(listItem))
FailedList.Add(listItem);
}
}
foreach (var item in FailedList)
{
Console.WriteLine(item);
}
Console.ReadLine();

Remove item from Observable Collection in Nested Foreach [duplicate]

This question already has answers here:
Collection was modified; enumeration may not execute error when removing a ListItem from a LIstBox
(10 answers)
Closed 8 years ago.
I have these nested Foreach :
foreach (var item1 in ocChoicesinItem)
{
foreach (var item2 in temp.ItemsInInvoiceChoices)
{
if (item1.ChoicesId == item2.ChoicesId)
ocChoicesinItem.Remove(item1);
}
}
The problem occur when remove item from ocChoicesinItem, gives me this error:
Is there any way to accomplish this?
Thanks in advance.
You need to add 'ToList' statements if you want to remove items in the collection :
foreach (var item1 in ocChoicesinItem.ToList())
{
foreach (var item2 in temp.ItemsInInvoiceChoices)
{
if (item1.ChoicesId == item2.ChoicesId)
ocChoicesinItem.Remove(item1);
}
}
You can't modify a collection while iterating that collection, as you are making your Enumerator invalid when calling MoveNext
Try:
public static class ExtensionMethods
{
public static int RemoveAll<T>(
this ObservableCollection<T> coll, Func<T, bool> condition)
{
var itemsToRemove = coll.Where(condition).ToList();
foreach (var itemToRemove in itemsToRemove)
{
coll.Remove(itemToRemove);
}
return itemsToRemove.Count;
}
}
ocChoicesinItem.RemoveAll(x => temp.ItemsInInvoiceChoices.Any(y => y.ChoicesId == x.ChoicesId);
Try something like
List<string> ocChoicesinItem = new List<string>{"One", "Two", "Three"};
List<string> ItemsInInvoiceChoices = new List<string> { "Three" };
ocChoicesinItem.RemoveAll(x => ItemsInInvoiceChoices.Contains(x));
Obviously I am using strings as I don't know what type your collections contain; you may have to compare the ID's in the predicate.

Grouping Items In A List View

I have a Dictionary that is declared thusly:
Dictionary myDictionary<string, List<FCPort>> = new Dictionary<string, List<FCPort>>();
the key is a string representing a switch name. The value is a list of port objects for that switch. I am trying to add the items in the Dictionary to a ListView with this code:
foreach (KeyValuePair<string, List<FCPort>> portpair in results)
{
ListViewItem item1 = new ListViewItem(portpair.Key);
foreach (FCPort port in portpair.Value)
{
item1.SubItems.Add(port.FCIDList[0]);
item1.SubItems.Add(port.WWPNList[0]);
item1.SubItems.Add(port.TextSerializePortName());
this.ResultsListView.Items.Add(item1);
}
}
However, I get a run-time error basically saying that I have a duplicate item in the list. That makes sense. I am attempting to group by the dictinoary key (the switch name). Is there a way to somehow group the items in the listview, or dynamically add Listviews to the GroupBox on the fly? Basically add a new ListView for each key in the Dictionary? I am still learning C# and forms are still new.
you could use LINQ lookup to group by your key selector.
and extend your portpair to enumerable when add to into listview subitems
This is the code snippet I did sometimes hopefully could help you.
Dictionary<String, Country> dict = new Dictionary<string, Country>();
dict.Add("Toronto", Country.Canada);
dict.Add("New York", Country.US);
dict.Add("Vancover", Country.Canada);
dict.Add("Seattle", Country.US);
dict.Add("Fredericton", Country.Canada);
Lookup<Country,String> lookup = (Lookup<Country,String>) dict.ToLookup(pair =>pair.Value, pair => pair.Key);
foreach (var countryGroup in lookup)
{
item = new ListViewItem(countryGroup.Key.ToString());
item.SubItems.Add(string.Format("{0}", string.Join(",", countryGroup.Select(s => "#" + s))));
lv.Items.Add(item);
item = null;
}

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