The KeyValue pair class stores a pair of values in a single list.
It’s super easy to create a list of single value. Here is an example;
List<string> firstList = new List<string> {"'cover page$'", "'i# milestones$'", "'ii# tasks$'" };
List<string> secondList = new List<string> { "'cover page$'", "'i# milestones$'", "'ii# tasks$'" };
var exceptList = secondList.Except(firstList);
Console.WriteLine($"\nsingle string: Value in second list that are not in first List");
foreach (var val in exceptList)
{
Console.WriteLine($"single string: {val}");
}
What if we want to store pair of values instead of creating any custom classes? We can use KeyValue pair class;
var parentList = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("v2-2021", "'cover page$'"),
new KeyValuePair<string, string>("v2-2021", "'i# milestones$'"),
new KeyValuePair<string, string>("v2-2021", "'ii# tasks$'"),
new KeyValuePair<string, string>("v2-2021", "'iii# spendplan$'"),
};
var parentSubList = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("v2-2021", "'cover page$'"),
new KeyValuePair<string, string>("v2-2021", "'i# milestones$'"),
new KeyValuePair<string, string>("v2-2021", "'ii# tasks$'"),
};
var exceptList1 = parentSubList.Except(parentList);
Console.WriteLine($"\nparentSubList->parentList: Value in second list that are not in first List");
foreach (var val in exceptList1)
{
Console.WriteLine($"{val}");
}
IsASubset = parentSubList.All(i => parentList.Contains(i));
Console.WriteLine($"\nparentSubList->parentList: all members of subset (parentSubList) exists in list1 (parentList): {IsASubset}");
}
KeyValue pair class can also be used like this;
var myList = new List<KeyValuePair<string, string>>();
//add elements now
myList.Add(new KeyValuePair<string, string>("v2-2021", "'cover page$'"));
myList.Add(new KeyValuePair<string, string>("v2-2021", "'i# milestones$'"));
myList.Add(new KeyValuePair<string, string>("v2-2021", "'ii# tasks$'"));
foreach (var val in myList)
{
Console.WriteLine($"Another style: {val}");
}
LINQ methods, for example Except can be used without implementing any Comparer classes.
Add to favorites