Reputation: 113
I have the below code where I want to read the value of dictionary 'filter' using for loop.'filter[1]'again has two values. Since dictionary is key value pair, how do I access the element value below.
class program
{
public string RecSys { get; set; }
public string AnsSys { get; set; }
public string IsAddOn { get; set; }
public string Country { get; set; }
public static void Main()
{
program p1 = new program();
program p2 = new program();
program p3 = new program();
List<program> List = new List<program>();
p1.RecSys = "RY1";
p1.AnsSys = "CSCLRC";
p1.IsAddOn = "P";
p1.Country = "India";
List.Add(p1);
p2.RecSys = "RY1";
p2.AnsSys = "APEX";
p2.IsAddOn = "primary";
p2.Country = "Pakistan";
List.Add(p2);
p3.RecSys = "RY1";
p3.AnsSys = "APEX";
p3.IsAddOn = "Addon";
p3.Country = "Pakistan";
List.Add(p3);
var filter = List.GroupBy(item => new { item.RecSys, item.AnsSys }).ToDictionary(grp => grp.Key, grp => grp.ToList()).Values;
for (int i = 0; i < filter.Count; i++)
{
// read the values. 'filter[1]'again has two values
}
}
}
Upvotes: 0
Views: 28
Reputation: 21795
You can fetch the values using two foreach
loop like this:-
foreach (var item in filter)
{
foreach (var innerItem in item)
{
Console.WriteLine(innerItem.IsAddOn);
Console.WriteLine(innerItem.Country);
//and so on..
}
}
Or else if you want all the Values
of dictionary at once then you can flatten it using SelectMany:-
var filter = List.GroupBy(item => new { item.RecSys, item.AnsSys })
.ToDictionary(grp => grp.Key, grp => grp.ToList())
.SelectMany(x => x.Value);
and finally iterate over the items using a single foreach
loop:-
foreach (var item in filter)
{
Console.WriteLine(item.Country);
Console.WriteLine(item.AnsSys);
//and so on..
}
Upvotes: 2