gpt4 book ai didi

c# - 如何使用 LINQ 生成数据透视表?

转载 作者:行者123 更新时间:2023-11-30 20:01:10 27 4
gpt4 key购买 nike

在将其作为重复项关闭之前,请注意我知道“[c#] [linq] pivot”上有很多问题,我花了一整天的时间试图解决这个问题,直到现在才求助于 SO。

我从数据库中以这种形式获取数据:

Item    Collection_Period   Value
==== ================= =====
Item3 201307 27.2
Item4 201308 19
Item3 201209 2.1
Item2 201307 345
Item1 201309 13.11
Item2 201308 34
Item3 200609 85
Item4 201308 58.2
Item3 201209 2.4
Item2 201309 12.1
Item1 201209 12.3

我需要将数据处理成这种格式:

Item    CurrMon-3   CurrMon-2   CurrMon-1
===== ========= ========= =========
Item1 13.11
Item2 345 34 12.1
Item3 27.2
Item4 19 58.2

(只需要显示最近三个月的数据)。我正在尝试这个:

var pivoted = new List<PivotedMeanData>();
var thisMonth = DateTime.Now.Month;
var p = meanData
.GroupBy(i => i.Description)
.Select(g => new PivotedMeanData
{
Description = g.Key,
M3 = g.Where(c => DateTime.ParseExact(c.CollectionPeriod, "yyyyMM", CultureInfo.InvariantCulture).Month == thisMonth - 3).ToString().Select(c => c.Value),
M2 = g.Where(c => DateTime.ParseExact(c.CollectionPeriod, "yyyyMM", CultureInfo.InvariantCulture).Month == thisMonth - 2).ToString().Select(c => c.Value),
M1 = g.Where(c => DateTime.ParseExact(c.CollectionPeriod, "yyyyMM", CultureInfo.InvariantCulture).Month == thisMonth - 1).ToString().Select(c => c.Value)
});
return pivoted;

我有一个类来保存这些数据:

public class PivotedMeanData
{
public string Description { get; set; }
public string M3 { get; set; }
public string M2 { get; set; }
public string M1 { get; set; }
}

MeanData类的定义:

public class MeanData
{
public string Description { get; set; }
public long SeqNo { get; set; }
public string CollectionPeriod { get; set; }
public long Value { get; set; }
}

我搜索了很多,找到了this question完全符合我的挑战。但是,如果我在 Where 谓词的末尾添加 .Select(c => c.Value) (因为我只需要那个时间段的值),代码就不会编译。

'char' does not contain a definition for 'Value'

提到的问题显示的是完全相同的东西(他们只是使用 sum 而不是 select)

我在这里做错了什么?我的尝试是完全错误的还是只是获取 Value 是错误的?

最佳答案

因为您正在对正在枚举该字符串中的字符的字符串调用 Select():

M3 = g.Where(c => DateTime.ParseExact(c.CollectionPeriod, 
"yyyyMM",
CultureInfo.InvariantCulture)
.Month == thisMonth - 3)
.ToString() // string
.Select(c => c.Value) //c = char

我怀疑你想要

M3 = g.Where(c => DateTime.ParseExact(c.CollectionPeriod, 
"yyyyMM",
CultureInfo.InvariantCulture)
.Month == thisMonth - 3)
.Sum(c => c.Value)

关于c# - 如何使用 LINQ 生成数据透视表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19450128/

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