【问题标题】:Retrieve three columns and group by one检索三列并按一分组
【发布时间】:2020-03-09 18:57:21
【问题描述】:


我有一个 SQL 表,由对应于字符数据的不同列组成(在游戏中)。
在这些列中,我想取 Level、Date(即数据已放在表上的时间),然后是与字符 Script 对应的字符串。

简而言之,我需要一个字典,或者一个以脚本为键的替代方案(在 c# 中肯定),并在值中包含一个 KeyValuePair 列表(也许?)。

比如这样的:(不是json,我只是代表我想要的)

"testScript" : 4 ; 09/03/2020 11:00:00,
               5 ; 09/03/2020 12:00:00,
               6 ; 10/03/2020 13:00:00,
               9 ; 10/03/2020 15:00:00,

"script7" : 7 ; 10/03/2020 14:00:00,
            8 ; 10/03/2020 14:30:00,

.....

是为了计算level平均值,把这个list转换成Json在google chart上画图。

这是我尝试过的一个示例,但它根本不起作用哈哈...

Dictionary<string, Tuple<int, DateTime>> lvlList = archivedCharacterList.Select(i => new { i.Level, i.Updated_at, i.Script_Name })
                                                                                                   .GroupBy(c => c.Script_Name)
                                                                                                   .OrderBy(g => g.Key.Updated_at)
                                                                                                   .ToList();

感谢您的宝贵时间!


更新(解决方案):
感谢@StriplingWarrior

 ILookup<string, (int, DateTime)> lvlList = archivedCharacterList
   .Select(i => new { i.Level, i.Updated_at, i.Script_Name })
   .OrderBy(g => g.Updated_at)
   .ToLookup(c => c.Script_Name, c => (c.Level, c.Updated_at)); 

    foreach (var line in lvlList)
     {
         Console.WriteLine(line.Key); // Script 
         foreach ((byte, DateTime) items in line)
         Console.WriteLine("{0} {1}", items.Item1, items.Item2);
     }
// Then I just have to add this to what I want :)

效果很好

【问题讨论】:

  • 能分享一下archivedCharacterList中item的类型定义吗?
  • Level 是 int,Updated_at 是 DateTime,Script 是 string
  • 请发布您的表的`CREATE TABLED 语句并发布一些示例源数据(到目前为止,您只发布了示例输出数据)

标签: c# arrays linq


【解决方案1】:

您需要ILookup(如果您需要能够按索引进行查找)。

ILookup<string, (int, DateTime)> lvlList = archivedCharacterList
    .Select(i => new { i.Level, i.Updated_at, i.Script_Name })
    .OrderBy(g => g.Updated_at)
    .ToLookup(c => c.Script_Name, c => (c.Level, c.Updated_at));

【讨论】:

    猜你喜欢
    • 2022-11-12
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多