gpt4 book ai didi

c# - 如何在 C# 中的枢轴后创建两个暗数组

转载 作者:太空宇宙 更新时间:2023-11-03 19:49:39 25 4
gpt4 key购买 nike

我从第 3 方收到一个 Json 文档,反序列化后,我有一个以下格式的动态对象列表

period       key          val
"2013-3" 0 5
"2013-3" 1 6
"2013-3" 2 5
"2013-3" 3 6
"2013-3" 4 15
"2013-3" 5 25
"2013-3" ">5" 55
"2013-3" "mykey1" 25
"2013-3" "mykey2" 6
"2013-4" 0 15
"2013-4" 1 16
"2013-4" 2 25
"2013-4" 3 36
and so on...

首先,我需要从该数据中删除 mykey1mykey2,我应该可以使用 LinQ 中的 where 子句来完成

.Where(w => (string)w.key != "mykey1" && (string)w.key != "mykey2")

完成后,我需要以列为键(从 0 到 5 排序,然后是字符串“>5”)对数据进行透视,并获得值的二维数组 int[,]。我不知道怎么做!

所以结果可能类似于下面..

int[,] activities= { 
{5,6,5,6,15,25,55},
{15,16,25,36,21,22,23},
{31,32,33,34,31,32,33},
{41,42,43,44,41,42,43},
{11,12,13,14,11,12,13},
{21,22,23,24,21,22,23},
{31,32,33,34,31,32,33},
{41,42,43,44,41,42,43},
{11,12,13,14,11,12,13},
{21,22,23,24,21,22,23},
{31,32,33,34,31,32,33},
{41,42,43,44,41,42,43}
};

最佳答案

我想你想要这样的东西:

var result = list.GroupBy(g => g.period).Select(c => new
{
period = c.Key,
s0 = c.Sum(f=> f.key.ToString() == "0" ? f.val : 0),
s1 = c.Sum(f=> f.key.ToString() == "1" ? f.val : 0),
s2 = c.Sum(f=> f.key.ToString() == "2" ? f.val : 0),
s3 = c.Sum(f=> f.key.ToString() == "3" ? f.val : 0),
s4 = c.Sum(f=> f.key.ToString() == "4" ? f.val : 0),
s5 = c.Sum(f=> f.key.ToString() == "5" ? f.val : 0),
s6 = c.Sum(f=> f.key.ToString() == ">5" ? f.val : 0),
})
.ToList();

结果会是这样的:

{ period = "2013-3", s0 = 5,  s1 = 6,  s2 = 5,  s3 = 6,  s4 = 15, s5 = 25, s6 = 55 }
{ period = "2013-4", s0 = 15, s1 = 16, s2 = 25, s3 = 36, s4 = 21, s5 = 22, s6 = 23 }
...

动态版本可以是这样的:

var result = list.GroupBy(g => g.period)
.ToDictionary(k => k.Key, l =>
list.Where(w => w.period == l.Key)
.GroupBy(k => k.key.ToString())
.OrderBy(o => o.Key)
.Select(s => s.Sum(f => f.val)));

这会返回句点键的字典和基于键的求和值列表;)。

编辑:

var result = list.GroupBy(g => g.period)
.Select(l =>
list.Where(w => w.period == l.Key && !w.key.In(new[] {"myKey1", "myKey2"}))
.GroupBy(k => k.key == ">5" ? "6" : k.key.ToString())
.OrderBy(o => o.Key)
.Select(s => s.Sum(f => f.val))
.ToArray())
.ToArray();

关于c# - 如何在 C# 中的枢轴后创建两个暗数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41322712/

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