Venkat
Venkat

Reputation: 2156

Group by for IEnumerable object in Linq

I have the following json file

{

  "questions": [
    {
      "GroupBy": "Information Security Policies",
      "IdentifiedRisk": "some question 1",
      "Yes_No_NA": null,
      "Comments_Discussion": null,
      "Likelihood": null,
      "Severity": null,
      "Rating": 0,
      "RiskWeightage": 7,
      "ControlCategory": "A.5.1"
    },
    {
      "GroupBy": "Organization of Information Security",
      "IdentifiedRisk": "some question 2",
      "Yes_No_NA": null,
      "Comments_Discussion": null,
      "Likelihood": null,
      "Severity": null,
      "Rating": 0,
      "RiskWeightage": 7,
      "ControlCategory": "A.6.1"
    },
    {
      "GroupBy": "Human Resource Security",
      "IdentifiedRisk": "some question 3",
      "Yes_No_NA": null,
      "Comments_Discussion": "some comments and discussion",
      "Likelihood": null,
      "Severity": null,
      "Rating": 0,
      "RiskWeightage": 7,
      "ControlCategory": "A.7.1"
    },
    {
      "GroupBy": "Human Resource Security",
      "IdentifiedRisk": "some question 3.1?",
      "Yes_No_NA": null,
      "Comments_Discussion": "some comments and discussion",
      "Likelihood": null,
      "Severity": null,
      "Rating": 2,
      "RiskWeightage": 5,
      "ControlCategory": "A.7.2"
    },
  ]
}

And the corresponding class files:

public class Questionnaire
{
    public string? GroupBy { get; set; }
    public string? IdentifiedRisk { get; set; } //actual question.

    [Required]
    public string? Yes_No_NA { get; set; }
    public string? Comments_Discussion { get; set; }
  
    public string? Likelihood { get; set; }
    public string? Severity { get; set; }

    public int? Rating { get; set; } //rating given after selectionof answers if yes =1 and no or n/a it is riskweightable
    public int? RiskWeightage { get; set; } //a numerical number.
    public string? Scoring { get; set; } //Low, Medium, High, Critical

    public string? ControlCategory { get; set; } //question number
}

public class RootQuestions
{
    public List<Questionnaire>? questions { get; set; }
}

Now I want to group by, using the GroupBy function, and display questions for every group and manipulate them.

How do we do this in Linq? I am new to Linq.

Upvotes: 0

Views: 125

Answers (1)

Mohammad Aghazadeh
Mohammad Aghazadeh

Reputation: 2825

using System.Text.Json;



var jsonStr= File.ReadAllText("Json File Path");

var result = JsonSerializer.Deserialize<RootQuestions>(jsonStr);

var questionGroups = result?.questions?.GroupBy(q => q.GroupBy, (key, items) => new { GroupName = key, Questions = items.ToList() }).ToList();

questionGroups?.ForEach(data =>
{
   Console.WriteLine($"GroupName :{data.GroupName}");

   foreach (var q in data.Questions)
   {
       Console.WriteLine(q.IdentifiedRisk);
      //Other Properties
   }
});

Upvotes: 2

Related Questions