Compare values in Dictionary with Another List Items - c#

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

Related

C# dictionary value is updating automatically

In my recent project im trying to make a dictionary with key as a string and value as List of string(List) and adding value in dictionary using for loop ,
but the problem is that after first iteration when I Update the List for second iteration it is automatically changing in the first key value pair.
for example in first iteration it is saving key as apple and value as list {cucumber,chilli,tomato,apple} its fine but after first iteration when i update list to {cucumber,chilli,tomato,apple,mango} and saving it to second key mango it is also updating the first value to {cucumber,chilli,tomato,apple,mango}.
var mylist = new List<string>()
{
"cucumber",
"chilli",
"tomato"
};
var yourlist = new List<string>()
{
"apple",
"mango",
"banana"
};
var dict = new Dictionary<string, List<string>>();
foreach (var i in yourlist)
{
mylist.Add(i);
dict.Add(i,mylist);
}
foreach(var d in dict.Keys)
{
foreach(var l in dict[d])
{
Console.WriteLine(l);
}
}
The dictionary entries' Value properties are always the same list, so anything you do to one, ends up showing in all of them (because there is only one)
Take a look at the code below; if you understand why a and b here both show the same change, then you should understand that your dictionary scenario is essentially the same
var list = new List<string>(){ "hello", "world" };
var a = list;
var b = list;
a.Add("there");
Console.Write(b.Count); //shows 3
If you don't understand why a, b and list above all refer to the same list, then drop a comment and I'll add some more explanation
As to what you should do about your "issue", it's not entirely clear to me what you're hoping to do but if you made sure that each key in the dictionary associated with a new list rather than the same one, then changes to one key's list would not show in other keys' lists:
dict.Add(i, new List<string>(mylist));
This makes a new list per key, and initializes the new list with the items present in mylist at the time (my list grows each pass of the loop)

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 Items To a existing List In a dictionary

I have a dictionary as below
var dicAclWithCommonDsEffectivity = new Dictionary<string, List<int>>();
I have a list as below
var dsList=new List<int>();
For each item in dsList I will search in dicAclWithCommonDsEffectivity dictionary for the matching values in the list. If i find a match I take its Keys and form a new Key combining all the keys. I will create a new list and add item.
foreach (int i in dsList)
{
var aclWithmatchingDS = dicAclWithCommonDsEffectivity.Where(x => x.Value.Contains(i)).Select(x=>x.Key);
if (aclWithmatchingDS.Count() > 0)
{
string NewKey= aclWithmatchingDS.key1+","aclWithmatchingDS.key2 ;
//if NewKey is not there in dictionary
var lst=new List<int>(){i};
//Add item to dictionary
//else if item is present append item to list
//oldkey,{oldlistItem,i};
}
}
For the next item in dsList if there is a matching key then I have to add the item to the list inside new dictionary.
How to add new item to the list in a dictionary without creating new list.
You probably want something like that:
if (dicAclWithCommonDsEffectivity.ContainsKey(NewKey))
{
dicAclWithCommonDsEffectivity[NewKey].Add(i)
}
else
{
dicAclWithCommonDsEffectivity.Add(NewKey, lst); // or simply do new List<int>(){ i } instead of creating lst earlier
}
I suggest TryGetValue method which is typical in such cases:
List<int> list;
if (dicAclWithCommonDsEffectivity.TryGetValue(NewKey, out list))
list.Add(i);
else
dicAclWithCommonDsEffectivity.Add(NewKey, new List<int>() {i});
In case of C# 7.0 you can get rid of list declaration:
if (dicAclWithCommonDsEffectivity.TryGetValue(NewKey, out var list))
list.Add(i);
else
dicAclWithCommonDsEffectivity.Add(NewKey, new List<int>() {i});
Get first KeyValue pair in dicAclWithCommonDsEffectivityand add it to the list, which is the value here and it can be accessed directly:
if (aclWithmatchingDS.Count() > 0)
{
dicAclWithCommonDsEffectivity.Add(NewKey,lst);
}
else
{
aclWithmatchingDS.First().Value.Add("Here add your item");
}
Let me clarify before suggestion, So You want to check for existance of a key in the dictionary, according to some condition, If specific key is present means you want to add the new item to corresponding key or else you want to create a new key and a new list with the new item, if I understand the requirement correctly means you can try the following:
if(dicAclWithCommonDsEffectivity.ConainsKey(NewKey))
{
aclWithmatchingDS[NewKey].Add(i);
}
else
{
aclWithmatchingDS.Add(NewKey, new List<int>(){i});
}

C# - Remove items from List when button is clicked

My problem is; When click a button I input items in List, next in DropDownList. Problem is where i click button again exist items again into my DropDown.
How to solve this problem(sorry for image)?
List<string> companyList = new List<string>();
foreach (string item in companyList.ToList())
{
companyList.Remove(item); ----> this not working.......
}
foreach (SPListItem item in myItemCol)
{
companyList.Add(item["Company"].ToString());
}
companyList.Sort();
foreach (string item in companyList.Distinct())
{
ddComFilter.Items.Add(item.ToString());
}
You can use the Contains method to check if it is already there
if(!ddComFilter.Items.Contains(items.ToString())
{
ddComFilter.Items.Add(item.ToString());
}
This will only add the item if it is not already in the dropdown
You could check for existence of the item before add it to the list.
foreach (SPListItem item in myItemCol)
{
if(!companyList.Contains(item["Company"].ToString())
{
companyList.Add(item["Company"].ToString());
}
}
Then you need to clear the ddComFilter before adding the values to it:
companyList.Sort();
ddComFilter.Items.Clear();
foreach (string item in companyList.Distinct())
{
ddComFilter.Items.Add(item.ToString());
}
Alternate solution:
You can bind the ddComFilter using the generated list, instead for iterating the collection and add one-by-one. if so you need not to clear the collection, remove items etc. The code for this will be:
ddComFilter.Datasource = companyList;
ddComFilter.DataBind();
Here is an useful article for you
You should clear your dropdown before adding list as items:
companyList.Sort();
ddComFilter.Items.Clear(); // clear
foreach (string item in companyList.Distinct())
{
ddComFilter.Items.Add(item.ToString());
}

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

Categories