2

I have two classes

public class MyObjects{
  public bool Active {get; set;}
  public List<OtherObject> OtherObjects {get; set;}
}

public class OtherObject {
  public int Id {get; set;}
  public bool Enabled {get; set;}
  public string Address {get; set;}
  public string Name {get; set;}
}

My current result is

MyObject { Active = true; }, 
OtherObjects: [OtherObject: { Id: 1, Name: 'First'}, 
OtherObject{Id: 2, Name: 'First'}, 
OtherObject{Id: 3, Name: 'Second'}];

I want to group them by Name so I would still have Active property and those OtherObjects inside would be grouped by OtherObject Name property. Is it possible to do so only using LINQ?

EDIT: Final result should be json, that I will use in angular, so it should be something like this:

{
  ""Active"": true,
  ""OtherObjects"": [
    {
      ""ObjectName"": ""Second"",
      ""ObjectOtherProperties"": [
        {
          ""Id"": 1,
          ""Enabled"": false
        },
        {
          ""Id"": 2,
          ""Enabled"": true
        }
      ],
      ""ObjectName"": ""Second"",
      ""ObjectOtherProperties"": [
        {
          ""Id"": 1,
          ""Enabled"": false
        }
      ],
    ]
  }
}

Any suggestions how to achieve this? Maybe I must make other classes and somehow map them by grouping?

4
  • 3
    It's very unclear to me what the result would look like, I'm afraid - the "my current result" part is sort of JSON but not quite... it would be much easier to help you with a short but complete example. LINQ's GroupBy is very likely to be what you want, but it's hard to tell at the moment. Commented Dec 3, 2015 at 7:15
  • yes, I would like to have a JSON at the end, but I don't know how to explain it clearly. I'll try to update somehow to show result, that I want to have at the end Commented Dec 3, 2015 at 7:20
  • I want to group them by Name There is no name property in MyObjects, only in OtherObjects (which you are grouping in the child collection). Could you give us the exact model you have and the one you want? Some of the properties don't match up (name vs objectname), etc. There's currently a lot of guess work for us to do to figure out a solution Commented Dec 3, 2015 at 7:34
  • Question seems unclear, can you provide exact data model and required output json structure Commented Dec 3, 2015 at 7:42

2 Answers 2

1

This is how I would do it, keeping it simple:

// 1. Add OtherObjectsDictionary
// 2. Block OtherObjects in the json serialization
public class MyObjects
{

    public bool Active { get; set; }

    [Newtonsoft.Json.JsonIgnore]
    public List<OtherObject> OtherObjects { get; set; }

    public Dictionary<string, List<OtherObject>> OtherObjectsDictionary { get; set; }

}

// 3. Block Name in the json serialization
public class OtherObject
{

    public int Id { get; set; }

    public bool Enabled { get; set; }

    public string Address { get; set; }

    [Newtonsoft.Json.JsonIgnore]
    public string Name { get; set; }

}

// 4. Linq queries to achieve the grouped result
// 5. Serialize to Json
static void Main(string[] args)
{

    var myObjects = new MyObjects() { Active = true, OtherObjects = new List<OtherObject>() };
    myObjects.OtherObjects.Add(new OtherObject { Id = 1, Name = "First" });
    myObjects.OtherObjects.Add(new OtherObject { Id = 2, Name = "First" });
    myObjects.OtherObjects.Add(new OtherObject { Id = 3, Name = "Second" });

    myObjects.OtherObjectsDictionary = new Dictionary<string, List<OtherObject>>();
    var distinctNames = myObjects.OtherObjects.Select(otherObject => otherObject.Name).Distinct();
    foreach(var distinctName in distinctNames)
    {
        var groupedObjectsList = myObjects.OtherObjects.Where(otherObject => otherObject.Name == distinctName).ToList();
        myObjects.OtherObjectsDictionary.Add(distinctName, groupedObjectsList);
    }

    var outputJson = Newtonsoft.Json.JsonConvert.SerializeObject(myObjects);

}   

This is the json result:

{
  "Active": true,
  "OtherObjectsDictionary": {
    "First": [
      {
        "Id": 1,
        "Enabled": false,
        "Address": null
      },
      {
        "Id": 2,
        "Enabled": false,
        "Address": null
      }
    ],
    "Second": [
      {
        "Id": 3,
        "Enabled": false,
        "Address": null
      }
    ]
  }
}

I hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

1

You may also use the System.Web.Extensions .dll as Add References for framework 4.0 projects (not 4.0 Client Profile).

enter image description here

Then add using inside your class. enter image description here

I also applied a different approach, a more-or-less DB like normalization.

List of classes

        public class MyObjects
        {
            public bool Active { get; set; }
            public List<ObjectName> OtherObjects { get; set; }
        }

        public class ObjectName
        {
            public string Name { get; set; }
            public List<OtherObject> OtherObjectProperties { get; set; }
        }

        public class OtherObject
        {
            public int Id { get; set; }
            public bool Enabled { get; set; }
            [ScriptIgnore]
            public string Address { get; set; }
            [ScriptIgnore]
            public string Name { get; set; }
        }

populate the records..

            List<OtherObject> oList = new List<OtherObject>();
            oList.Add(new OtherObject() { Id = 2, Name = "First" });
            oList.Add(new OtherObject() { Id = 3, Name = "Second" });

            // each name with objects
            List<ObjectName> oNames = new List<ObjectName>();
            oNames.AddRange(oList.Select(p => new ObjectName() { 
                   Name = p.Name
                   , OtherObjectProperties = oList.Where(p1 => p1.Name == p.Name).ToList()
            }).Distinct()
            );

            // parent object with with object names
            MyObjects mo = new MyObjects() { Active = true, OtherObjects = oNames };

and finally, the javascript serializer..

JavaScriptSerializer jss = new JavaScriptSerializer();
string b = jss.Serialize(mo);

string b should give you the output like below..

{
"Active":true
,"OtherObjects":[
{
    "Name":"First"
    ,"OtherObjectProperties":[
    {
        "Id":2
        ,"Enabled":false}
    ]},
    {
    "Name":"Second"
    ,"OtherObjectProperties":[
    {
        "Id":3
        ,"Enabled":false}
    ]
}]
}

Please advise if you're confused about any of the following.. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.