2015-07-02 2 views
0

У меня есть цикл foreach, в котором значения повторяются, и я хотел бы группировать значения значения и out put только один раз. мой код выглядит следующим образомЗначение цикла цикла forach только один раз, если оно повторяется

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"); 
    } 
    <[email protected](Ved, "VED")--> @priceQuantity <[email protected](Count, "STK")-->. - <[email protected](Count, "STK")-->. <[email protected](Price, "PRIS")-->. @i.GetValue("Ecom:Product.Prices.AmountFormatted")<br/> 
    } 

, который дает следующее из положить 1 СТК, 1 СТК, 1 СТК, 12 СТК, 8 СТК, 8 СТК, 1 СТК

я хотел выводить его как 1 СТК, 12 СТК, 8 СТК

Как я могу добиться этого результата, пожалуйста, помогите

+0

Вы пробовали использовать словарь для хранения значений, которые вы отпечатанные? Затем вы можете проверить, присутствует ли значение в словаре перед его печатью; –

ответ

1
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"); 
     } 
     <[email protected](Ved, "VED")--> @priceQuantity <[email protected](Count, "STK")-->. - <[email protected](Count, "STK")-->. <[email protected](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"); 
      } 
      <[email protected](Ved, "VED")--> @priceQuantity <[email protected](Count, "STK")-->. - <[email protected](Count, "STK")-->. <[email protected](Price, "PRIS")-->. @i.GetValue("Ecom:Product.Prices.AmountFormatted")<br/> 
     }    
} 
2

вы можете сделать как эту принять перечислимую коллекцию, то

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

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

Это даст вам один предмет для количества

+0

Этот ответ классный. Действительно хорошо. Кстати, это LINQ. –

0

Использование Distinct() как:

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

Должен работать.

Смежные вопросы