gpt4 book ai didi

c# - 使用 LINQ 的条件 Group By 语句

转载 作者:太空狗 更新时间:2023-10-30 01:12:12 24 4
gpt4 key购买 nike

我有一个看似相当简单的要求,但环顾四周我无法得到一个简单的答案。我查看了 MSDN 论坛、Exper Exchange,但没有提供任何实质性内容。

我有以下 LINQ 代码

Dim SummaryLog As IQueryable(Of clPartCountSummary)    
SummaryLog = From Inventory In db.tblPartCounts _
Where Inventory.InventoryCountId = InventoryCountId _
And Not Inventory.ActionId.HasValue _
Group By PartNumber = Inventory.PartNumber _
, Inventory.RevLevel, SAPLocation = Inventory.SAPLocation _
Into AggregatedProdLog = Group, Qty = Sum(Inventory.Quantity) _
Select New clPartCountSummary With
{.PartNumber = PartNumber,
.RevLevel = RevLevel,
.Qty = Qty,
.SAPLocation = SAPLocation}

我希望能够根据 RevLevelSAPLocation 进行有条件的分组。我将始终按 PartNumber 分组,但其他两个是可选的。因此,如果变量 bRevLevel 为真,则我们按 RevLevel 分组,如果 bSAPLocation 为真,则我们按 SAPLocation 分组

非常感谢任何帮助,我正处于多个 SummaryLog 定义开始看起来很有吸引力的阶段。

谢谢,托马斯

最佳答案

希望这对您有所帮助....

public class TblPartCount
{
public int InventoryCountID { get; set; }
public int? ActionID { get; set; }
public string PartNumber { get; set; }
public int RevLevel { get; set; }
public string SAPLocation { get; set; }
public int Quantity { get; set; }
}

private static void ConditionalGroupBy()
{
bool pCheck = true;

var lList = new List<TblPartCount>
{
new TblPartCount { InventoryCountID = 1, ActionID = 2, PartNumber = "123", RevLevel = 1, SAPLocation = "AAAA", Quantity = 100 },
new TblPartCount { InventoryCountID = 1, ActionID = 2, PartNumber = "123", RevLevel = 1, SAPLocation = "BBBB", Quantity = 200 }
};

var lOutput = lList
.Where(pArg => pArg.InventoryCountID == 1)
.Where(pArg => pArg.ActionID != null)
.GroupBy(pArg => new
{
PartNumber = pArg.PartNumber,
RevLevel = pCheck ? pArg.RevLevel : 0,
SAPLocation = pCheck ? pArg.SAPLocation : String.Empty
})
.Select(pArg =>
new
{
PartNumber = pArg.Key.PartNumber,
RevLevel = pArg.Key.RevLevel,
SAPLocation = pArg.Key.SAPLocation,
Qtry = pArg.Sum(pArg1 => pArg1.Quantity)
});

foreach (var lItem in lOutput)
{
Console.WriteLine(lItem);
}
}

关于c# - 使用 LINQ 的条件 Group By 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/965952/

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