Foreach 循环仅在重复时显示一次值

Foreach loop show value's only once if repeated

我有一个 foreach 循环,其中重复值,我只想对值和输出值进行一次分组。我的代码看起来像这样

foreach (LoopItem i in GetLoop("Product.Prices")){
    var priceQuantity = "";
    if(i.GetInteger("Ecom:Product.Prices.Quantity") == 0){
        priceQuantity = "1";
    } else if(i.GetInteger("Ecom:Product.Prices.Quantity") >= 1){
        priceQuantity = i.GetString("Ecom:Product.Prices.Quantity");
    }   
    <!--@Translate(Ved, "VED")--> @priceQuantity <!--@Translate(Count, "STK")-->. - <!--@Translate(Count, "STK")-->. <!--@Translate(Price, "PRIS")-->. @i.GetValue("Ecom:Product.Prices.AmountFormatted")<br/> 
    }

给出以下输出 1 个, 1 个, 1 个, 12 个, 8 个, 8 个, 1 stk

我想将其输出为 1 个, 12 个, 8 stk

我怎样才能实现这个输出请帮忙

你可以这样做然后获取可枚举集合

var collection = GetLoop("Product.Prices");

var firstItemsInGroup = from b in collection 
                 group b by b.Quantity into g
                 select g.First();

这将为您提供一件数量

像这样使用Distinct()

  foreach (LoopItem i in GetLoop("Product.Prices").Distinct())

应该可以。

var result = GetLoop("Product.Prices").GroupBy(x => x.Quantity).Select(x => x.First());

然后您可以根据您的条件打印结果集合。

    foreach (LoopItem i in result){
        var priceQuantity = "";
        if(i.GetInteger("Ecom:Product.Prices.Quantity") == 0){
            priceQuantity = "1";
        } else if(i.GetInteger("Ecom:Product.Prices.Quantity") >= 1){
            priceQuantity = i.GetString("Ecom:Product.Prices.Quantity");
        }   
        <!--@Translate(Ved, "VED")--> @priceQuantity <!--@Translate(Count, "STK")-->. - <!--@Translate(Count, "STK")-->. <!--@Translate(Price, "PRIS")-->. @i.GetValue("Ecom:Product.Prices.AmountFormatted")<br/> 
    }

但你也可以用另一种方式做到这一点,使用 HashSet<T>

var sequence = GetLoop("Product.Prices");
var alreadyIn = new HashSet<T>();
foreach(var i in sequence)
{
        if(alreadyIn.Add(i))// Returns false if item was already in set
        {
           if(i.GetInteger("Ecom:Product.Prices.Quantity") == 0){
               priceQuantity = "1";
           }else if(i.GetInteger("Ecom:Product.Prices.Quantity") >= 1){
             priceQuantity = i.GetString("Ecom:Product.Prices.Quantity");
           }
           <!--@Translate(Ved, "VED")--> @priceQuantity <!--@Translate(Count, "STK")-->. - <!--@Translate(Count, "STK")-->. <!--@Translate(Price, "PRIS")-->. @i.GetValue("Ecom:Product.Prices.AmountFormatted")<br/> 
        }              
}