Ravi Gadag
Ravi Gadag

Reputation: 15861

C# Linq Group by with Dictionary

I have following data

{
  "id": "0012",
  "Name": "User01",
  "Status": "NEW",
  "Urgency": "Urgent"
}, {
  "id : "0013",
  "Name": "User01",
  "Status": "NEW",
  "Urgency": "Urgent"
}, {
"id : "0014"
  "Name": "User01",
  "Status": "REJECTED",
  "Urgency": "Urgent"
} {
"id : "0015"
  "Name": "User02",
  "Status": "NEW",
  "Urgency": "PastDue"
}

I am trying to get the below output using Linq GroupBy. But, not able to get the exactly as per the output.

 var groupedUrgency = sampleData.GroupBy(x => new { x.Urgency });

            var data = groupedUrgency.Select(x => new 
                {
                Name = "NeedToGetTheName also",
                    NewItems = x.Where(z => z.Status == "NEW").ToDictionary(gdc => x.Key.Urgency, gdc => x.Count()),
                    RejectedItems = x.Where(z => z.Status == "REJECTED").ToDictionary(gdc => x.Key.Urgency, gdc => x.Count())
                })
                .ToList();

Is there any way we can the output below mentioned table. I need to get the User name and It's count for given Urgency property for each status.

Output

Upvotes: 0

Views: 183

Answers (1)

Selim Yildiz
Selim Yildiz

Reputation: 5370

You can first group by Name and then select count group by Urgency as follows:

 var data = sampleData.GroupBy(x => x.Name).Select(x => new
            {
                Name = x.Key,
                NewItems = x.Where(n => n.Status == "NEW").GroupBy(g => g.Urgency).Select(s => new { UrgentType =  s.Key, Count = s.Count() }),
                RejectedItems = x.Where(n => n.Status == "REJECTED").GroupBy(g => g.Urgency).Select(s => new { UrgentType = s.Key, Count = s.Count() }),
            }).ToList();

Upvotes: 1

Related Questions