I have a query in linq but i am unable to understand it, because i didn’t write this query. The query is below
string[] arr1 = new string[]
{
"Pakistan:4,India:3,USA:2,Iran:1,UK:0",
"Pakistan:4,India:3,USA:2,Iran:1,UK:0",
"India:4,USA:3,Iran:2,UK:1,Pakistan:0"
};
var count = arr1
.SelectMany(s => s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
.GroupBy(s => s.Split(':')[0], s => s.Split(':')[1])
.ToDictionary(g => g.Key,
g =>
{
var items = g.Distinct();
var result = new Dictionary<String, int>();
foreach (var item in items)
result[item] = g.Count(gitem => gitem == item);
return result;
});
// print the result
foreach (var country in count.Keys)
{
foreach (var ocurrence in count[country].Keys)
{
Console.WriteLine("{0} : {1} = {2}", country, ocurrence, count[country][ocurrence]);
}
}
Purpose of this query
this query is performed to achieve this: We want to know that how many times Pakistan comes with ‘0’ , how many times with ‘1’ ,2 ,3 , 4 , and we want to get this information for all countries . Please can anyone define it step by step .Thanks
Note : this query is compiled , has no errors and is working properly
Let’s look at the query, step by step
SelectMany takes the result of splitting on ‘,’ and combines the various splits back into a single IEnumerable
So at that stage, you have converted the array
arr1into a singleIEnumerable<string>with values like likeUSA:2GroupBy then groups that
IEnumberable<string>. It splits each entry likeUSA:2using the ‘:’ character. The left-hand side is the grouping key and the right-hand side is the value.ToDictionary transforms that grouping into a Dictionary. The key of the Dictionary entry is the grouping key (e.g.
USA). The value of the Dictionary entry is a new (anonymous) object:The anonymous object is constructed by going through and counting the unique occurrences of a given count (e.g. if the key is
USA, how many times is the value1) and returns that count.