gpt4 book ai didi

c# - 从 C# 中的对象中获取分组数据

转载 作者:行者123 更新时间:2023-11-30 21:43:13 26 4
gpt4 key购买 nike

我有一个数据:

data e1 = new data() { eventId = 1, eventName = "event1", hobbies = "hobbies1", note = "note1" };
data e2 = new data() { eventId = 1, eventName = "event1", hobbies = "hobbies2", note = "note2" };
data e3 = new data() { eventId = 2, eventName = "event2", hobbies = "hobbies3", note = "note3" };
data e4 = new data() { eventId = 2, eventName = "event2", hobbies = "hobbies4", note = "note4" };

我需要将其分组到 List<Event>基于 eventId 和 eventName 的类,eventDetails 应根据 eventId 和 eventName 分组为 List<EventDetails>包含“爱好”和“注意”值的属性。

public class Event
{
public int eventId { get; set; }
public string eventName { get; set; }
public List<EventDetails> eventDetails { get; set; }
}

//i want to get a List<Event> which group e1,e2 together and e3,e4 together

这能做到吗?不确定我需要从哪里开始。我可以使用的最佳解决方案是什么?

最佳答案

您可以使用 GroupBy实现这一点的 LINQ 方法:

data e1 = new data() { eventId = 1, eventName = "event1", hobbies = "hobbies1", note = "note1" };
data e2 = new data() { eventId = 1, eventName = "event1", hobbies = "hobbies2", note = "note2" };
data e3 = new data() { eventId = 2, eventName = "event2", hobbies = "hobbies3", note = "note3" };
data e4 = new data() { eventId = 2, eventName = "event2", hobbies = "hobbies4", note = "note4" };

data[] arr = { e1, e2, e3, e4 };

List<Event> groupedList = arr.GroupBy(i => i.eventId)
.Select(j => new Event()
{
eventId = j.First().eventId,
eventName = j.First().eventName,
eventDetail = j.Select(f => new EventDetails()
{
hobbies = f.hobbies,
note = f.note
}).ToList()
})
.ToList();

关于c# - 从 C# 中的对象中获取分组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41906560/

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