How to groupby List <KeyValuePair <string, string [] >> in C # .net
I have List<KeyValuePair<string, string[]>>
and I filled this list with below data and I used below code to populate list from datatable code:
dicArray = dtrd.AsEnumerable()
.Select(Row => Row["IDp"]).Distinct()
.Select(Id => new KeyValuePair<string, string[]>(
Id.ToString(),
dtrd.AsEnumerable()
.Where(Row => Row["IDp"].ToString() == Id.ToString())
.Select(Row => Row["date"].ToString())
.ToArray()))
.ToList();
data
1:
2017-2-1
2017-2-1
2017-2-1
2017-2-2
2017-2-2
2017-2-2
2:
2017-4-1
2017-4-1
3:
2017-3-1
2017-3-1
now i want to group this list by date in order to generate this output
1:
2017-2-1 count:3
2017-2-2 count:3
2:
2017-4-1 count:2
3:
2017-3-1 count:2
+3
source to share
1 answer
So you want to group by ID and date? First you need to SelectMany
flatten the arrays:
var query = list
.SelectMany(kv => kv.Value.Select(s => new { Id = kv.Key, Date = s }))
.GroupBy(x => new { x.Id, x.Date })
.Select(g => new { g.Key.Id, g.Key.Date, Count = g.Count() });
-
SelectMany
creates an anonymous type with two properties for each row in all arrays. -
GroupBy
creates one group for eachId
+ combinationDate
. - The final
Select
adds a propertyCount
.
As per your last comment:
var query = listKeyValue
.SelectMany(kv => kv.Value
.Select(arr => new
{
Id = kv.Key,
Fields = arr.Split(';')
}))
.Select(x => new
{
x.Id,
Date = x.Fields[0],
Number = x.Fields.Last()
})
.GroupBy(x => new { x.Date, x.Number })
.Select(g => new { g.Key.Date, g.Key.Number, Count = g.Count() });
+3
source to share