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

时间:2017-01-28 05:13:03

标签: c# grouping

我有一个数据:

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

我需要根据eventId和eventName将其分组到List<Event>类,并且eventDetails应按eventId和eventName分组为List<EventDetails>属性,包含'hobbies'和'note'值

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

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

2 个答案:

答案 0 :(得分:2)

您可以使用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();

答案 1 :(得分:1)

假设您有List对象,可以像

一样尝试
List<data> dataObjects = ...
List<Event> eventsData = dataObjects.Select(p=> new Event(){ eventId = p.eventId, eventName = p.eventName, 
                                    eventdetail = dataObjects.Where(q=> q.eventId == p.eventId).Select(r=> new EventDetails(){ hobbies = r.hobbies, note = r.note }).ToList() }).Distinct().ToList();

确保在Event类中有一个构造函数,用于初始化List,如

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

    public Event()
    {
        eventdetail = new List<EventDetails>();
    }
}