gpt4 book ai didi

c# - 对象中的 LINQ 分组

转载 作者:行者123 更新时间:2023-11-30 23:33:07 25 4
gpt4 key购买 nike

我有两个类(class)

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;}
}

我目前的结果是

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

我想按 Name 对它们进行分组,这样我仍然会有 Active 属性,而里面的那些 OtherObjects 将按 OtherObject 进行分组 名称 属性。是否可以只使用 LINQ 来做到这一点?

编辑:最终结果应该是 json,我将在角度中使用它,所以它应该是这样的:

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

有什么建议可以实现吗?也许我必须创建其他类并以某种方式通过分组映射它们?

最佳答案

我会这样做,保持简单:

// 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);

}

这是 json 结果:

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

希望对你有所帮助。

关于c# - 对象中的 LINQ 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34059834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com