C# 如何为以下输出编写Linq查询
输出: 商店1 商店2C# 如何为以下输出编写Linq查询,c#,linq,C#,Linq,输出: 商店1 商店2 如何在Linq C#中查询以下输出?要获得您想要实现的目标,需要执行2GroupBys。首先用于名称(存储),然后在其中按代码分组。最终,要从不同的行中获取所需的不同字段,这称为数据透视 Code Test1 Test2 11 Apple Mango 注意:您的数据中有一个错误-带有值的记录 甜菜根的类型应为Test2,而不是Test1 为了得到你想要的 我添加了所有的ToLists(),只是为了在调试时方便—它们不是必需的 您还可以将其转换为字典: va
如何在Linq C#中查询以下输出?要获得您想要实现的目标,需要执行2
GroupBy
s。首先用于名称
(存储),然后在其中按代码
分组。最终,要从不同的行中获取所需的不同字段,这称为数据透视
Code Test1 Test2
11 Apple Mango
值的记录
甜菜根的类型应为Test2
,而不是Test1
为了得到你想要的
ToLists()
,只是为了在调试时方便—它们不是必需的您还可以将其转换为字典:
var result = Shopping.GroupBy(item => item.Name)
.Select(group => new
{
Store = group.Key,
Items = group.GroupBy(item => item.Code)
.Select(innerGroup => new
{
Code = innerGroup.Key,
//This is the pivoting part - I create a "column" and collect under it all the values for that type
Test1 = innerGroup.Where(item => item.Type == "Test1").Select(item => item.Value).ToList(),
Test2 = innerGroup.Where(item => item.Type == "Test2").Select(item => item.Value).ToList(),
}).ToList()
}).ToList();
然后可以通过以下方式访问它:
result[“Store 1”][1]。Test1
要获得您想要实现的目标,您需要执行2GroupBy
s。首先用于名称
(存储),然后在其中按代码
分组。最终,要从不同的行中获取所需的不同字段,这称为数据透视
Code Test1 Test2
11 Apple Mango
值的记录
甜菜根的类型应为Test2
,而不是Test1
为了得到你想要的
ToLists()
,只是为了在调试时方便—它们不是必需的您还可以将其转换为字典:
var result = Shopping.GroupBy(item => item.Name)
.Select(group => new
{
Store = group.Key,
Items = group.GroupBy(item => item.Code)
.Select(innerGroup => new
{
Code = innerGroup.Key,
//This is the pivoting part - I create a "column" and collect under it all the values for that type
Test1 = innerGroup.Where(item => item.Type == "Test1").Select(item => item.Value).ToList(),
Test2 = innerGroup.Where(item => item.Type == "Test2").Select(item => item.Value).ToList(),
}).ToList()
}).ToList();
然后可以通过以下方式访问它:
result[“Store 1”][1]。Test1
你好,罗谢尔,你尝试过什么吗?闻起来像家庭作业……试试购物。GroupBy(x=>x.Name)
你好,罗谢尔,你尝试过什么吗?闻起来像家庭作业……试试购物。GroupBy(x=>x.Name)
@Rochelle-它对你有帮助吗?是的,不知怎么的,但是我不想得到列表形式的Test1和test2。没有列表我怎么能得到呢。@Rochelle-我当时真的不明白你想要什么样的输出。请解释一下。。因为根据您发布的内容,这是您想要的。我从代码中删除了.ToList(),但Test1和Test2没有值。@Rochelle-它有。这是因为它是一个延迟执行的函数。在调试中,您可以看到“结果视图扩展结果视图将枚举IEnumerable”@Rochelle-它对您有帮助吗?是的,不知怎么回事,但我不想以列表形式获取Test1和test2。没有列表我如何获取。@Rochelle-我当时不太明白您想要的输出是什么。请解释一下。。因为根据您发布的内容,这是您想要的。我从代码中删除了.ToList(),但Test1和Test2没有值。@Rochelle-它有。这是因为它是一个延迟执行的函数。在调试中,您可以看到“结果视图展开结果视图将枚举IEnumerable”
var stores = Shopping.GroupBy(item => item.Name)
.Select(group => new
{
Store = group.Key,
Items = group.GroupBy(item => item.Code)
.Select(innerGroup => new
{
Code = innerGroup.Key,
Test1 = innerGroup.Where(item => item.Type == "Test1").Select(item => item.Value).ToList(),
Test2 = innerGroup.Where(item => item.Type == "Test2").Select(item => item.Value).ToList(),
}).ToDictionary(key => key.Code, value => value)
}).ToDictionary(key => key.Store, value => value.Items);