Grouping Items In A List View - c#

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

Related

How to display items in a list with a description of what that list item is in c# console

I am trying to display a list sorted in descending order with each item being displayed with a description of what the value of the item is in VS console app. I’m just not sure how to display the description with each item
Eg. output:
Total monthly expenses//description of list item : $1000//item obtained from list and sorted
Home loan repayment: $700
Vehicle Installment: $300
Thank you
I cannot see where you are getting the description values from. A better way to do this would be to use Dictionary instead of a List.
double cost = textbox1.Text; // cost of item
string des = textbox2.Text; //description of item
//below code goes into a event to add each item cost+description
Dictionary<double, string> io = new Dictionary<double, string>();
io.Add(cost, des);
//below code goes into a event to display all items
foreach(KeyValuePair<double, string> val in io.OrderByDescending(i => i.Key)) {
Console.WriteLine("${0},{1}", val.Key, val.Value);
}
assuming you have fetched the data from the database, store the data in a dictionary collection. The key in the key-value pair of the dictionary set is the product description information, and the value is the specific price. You can first extract the value of the key in the dictionary set for sorting, and then extract the value value in the dictionary set according to the value of the key.
static void main(string[] args)
{
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("keyboard", 100);
d.Add("mouse", 80);
//get key
var val = d.Keys.ToList();
//sort
val.Sort();
foreach (var key in val)
{
Console.WriteLine(key);
}
}

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)

Need to create a custom object by looping the list in c# is it possible

I need to create a list object based on a list of key-value pair dynamically but I can't assign the key value in object by looping the list.
foreach (KeyValuePair<string, IEnumerable<string>> item in List)
{
string keyValue = item.Key.ToString();
object value = new { item.Key = item.Value };
somefunction(value);
}
the item.key will throw issue. Any suggestions for how to create an object while looping through the list.
For example if the item value is { key: "sampleKey" , value : "sampleValue"} i need to create an object as { "sampleKey" = "sampleValue" }. How can I achive this.
I believe the answer is IEnumerable<string> newList = item.Value; instead of object value = new { item.Key = item.Value };
You could do something with the dynamic keyword and the ExpandoObject (https://learn.microsoft.com/en-us/dotnet/api/system.dynamic.expandoobject?view=net-5.0), but if you're keys are so dynamic, I don't see a point of having them in a class/object at all. Rather store the data as a dictionary, which will then let you retreive data from strings as well.

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

Populating data to a nested Dictionary Collection

I have a collection
List<Employee> which contain Properties like
Name ,EmployeeID,Address,JobTitle and so on
For every employee there are few column which changes and based upon these few columns i need to update my Active Directory.
So i thot of creating a isEditable field for each column which will signify whether the column has changed or not for a particular employee . But it turns out that i need to create this field for all the columns and the number of columns also changes frequently .
So I came up with nested dictionary collection
Dictionary<int, Dictionary<object, bool>>
which will store the Employee ID as the key and the object type will store all the column names and bool by default will be false
But i don't know how to populate the above nested collection with List<Employee> Collection .
This is what i have tried till now
Dictionary<int, Dictionary<object, bool>> _isEditable = new Dictionary <int, Dictionary<object, bool>>();
foreach (var item in _empColl )
{
foreach (var type in _empColl .GetType ().GetProperties ())
{
_isEditable.Add (item.EmployeeID ,dict.Add (type.Name,false));
}
}
But its throwing error .I'm trying to get the metadata (column names ) from the _empColl for each EmployeeID
You can use LINQ below to get the result:
var _isEditable = _empColl.ToDictionary(item => item.EmployeeID,
item => item.GetType()
.GetProperties()
.ToDictionary(pro => pro.Name,
pro => false));

Categories