Reputation: 33
my first question on StackOverflow. I have searched the web but have not found such a specific case. I will try to be as specific as possible.
I have a Data
array of objects:
Data:
[
{ ID:"ID1", Name:"Name1", Date:"2015-08-21", TypeA:{ Count:1 }, TypeB:{ Count:2 } },
{ ID:"ID2", Name:"Name2", Date:"2015-08-21", TypeA:{ Count:3 }, TypeB:{ Count:4 } },
{ ID:"ID3", Name:"Name3", Date:"2015-08-23", TypeA:{ Count:5 }, TypeB:{ Count:6 } }
]
I am trying to group all these arrays of object into new objects based on the Type
Property, i.e. if the TypeX.Count > 0
then add it to the Type main object. Then add them based on the Date
property, if the dates are the same then merge them under the same date:
TypeA:
{
Dates:
[
{ Date: "2015-08-21",
Data:
[
{ ID: "ID1", Name: "Name1", Count: 1 },
{ ID: "ID2", Name: "Name2", Count: 3 }
]
},
{ Date: "2015-08-23",
Data:
[
{ ID: "ID3", Name: "Name1", Count: 5 }
]
}
]
},
TypeB:
{
Dates:
[
{ Date: "2015-08-21",
Data:
[
{ ID: "ID1", Name: "Name1", Count: 2 },
{ ID: "ID2", Name: "Name2", Count: 4 }
]
},
{ Date: "2015-08-23",
Data:
[
{ ID: "ID3", Name: "Name3", Count: 6 }
]
}
]
}
I have done this using Javascript, but now I need to transfer the whole logic to the server side - C#/linq.
Any help would be much appreciated.
Upvotes: 2
Views: 643
Reputation: 21825
You need GroupBy twice:-
var result = Data.GroupBy(x => x.Type)
.Select(x => new
{
TypeAB = x.Key,
Obj = x.GroupBy(z => z.Date)
.Select(z => new
{
Date = z.Key,
InnerObj = z.Select(i => new
{
Id = i.Id,
Name = i.Name,
Count = i.Count
})
}).ToArray()
});
First group by Type
, which will return the Key
(nothing but TypeA, TypeB etc.) and an IEnumerable (objects within each Type). Further Group this list by Date
and project the Key as well as other objects. Here I am projecting anonymous type you can select the actual Type
if you have one.
Upvotes: 1