2012-10-28 56 views
1
string sStoreStockFeed = ""; 
string sSeparator = ""; 

var distinctStoreIDList = skuStoreStockLevels.Select(x => x.Item1).Distinct(); 

    foreach (var storeID in distinctStoreIDList) 
    { 
     foreach (var item in skuStoreStockLevels) 
     { 
      if (item.Item1 == storeID) 
      { 
       // add this one to a job for this store 
         sStoreStockFeed += sSeparator + item.Item1.ToString() + "," + item.Item2.ToString() + "," + item.Item3.ToString(); 
         sSeparator = "|"; 
      } 
     } 
     // some code to process the string before moving on 
     sStoreStockFeed = ""; 
     sSeparator = ""; 
    } 

在上面的代碼片段skuStoreStockLevels恰好是一個類型爲元組的List,而Item1是StoreID。得到了一個明確的清單,然後遍歷(非清晰)列表來獲取每個適用的項目。效率低下的是,對於每個不同的項目(StoreID),重複對(大)內部列表進行迭代。什麼是根據其獨特值遍歷列表的有效方式?

+0

製作地圖'STOREID - > job',並遍歷列表一次。如果'storeID'尚未在地圖中,請添加新作業。否則將商店添加到作業的「storeID」中。 - 哦,這看起來很像C#,而不是C,所以我重複了它。 –

+0

你的sSeparator似乎很奇怪,這是故意的。我懷疑之後會很難閱讀sStoreStockFeed中的結果。你可能會得到這樣的結果:A,2,3 | A,4,5B,1,2C,3,4 | C,6,7 ... – Casperah

回答

4

更新:純粹的LINQ解決方案。這將爲您提供爲每組項目創建的字符串列表。

var query = skuStoreStockLevel.GroupBy(x => x.Item1) 
       .Select(g => g.Aggregate(new StringBuilder(), 
             (sb, x) => sb.AppendFormat("{0}{1},{2},{3}", sSeparator, x.Item1, x.Item2, x.Item3), 
             (sb) => sb.ToString())); 

foreach(var feed in query) 
    // some code to process the string before moving on 

此外還有其他選項 - 順序排序。相同的項目將接踵而至。

int storeID = -1; 
StringBuilder builder = new StringBuilder(); 

foreach (var item in skuStoreStockLevel.OrderBy(x => x.Item1)) 
{ 
    builder.AppendFormat("{0}{1},{2},{3}", sSeparator, item.Item1, item.Item2, item.Item3); 
    if (item.Item1 != storeID) 
    { 
     // some code to process the string before moving on 
     storeID = item.Item1; 
    }  
} 

或者您可以使用分組

StringBuilder builder = new StringBuilder(); 

foreach (var storeGroup in skuStoreStockLevel.GroupBy(x => x.Item1)) 
{ 
    foreach (var item in storeGroup) 
      builder.AppendFormat("{0}{1},{2},{3}", sSeparator, item.Item1, item.Item2, item.Item3);   

    // some code to process the string before moving on 
} 

,當然,最好是使用StringBuilder創建的字符串。

1

使用LINQ GroupBy這將爲你分組的項目清單:

string sStoreStockFeed = ""; 
string sSeparator = ""; 

var itemsByStore = skuStoreStockLevels.GroupBy(x => x.Item1); 
foreach (var storeItems in itemsByStore) 
{ 
    // storeItems.Key is the storeId, that is x.Item1 
    foreach(var item in storeItems) 
    { 
     sStoreStockFeed += sSeparator + item.Item1.ToString() + "," + item.Item2.ToString() + "," + item.Item3.ToString(); 
     sSeparator = "|"; 
    } 

    // some code to process the string before moving on 
    sStoreStockFeed = ""; 
    sSeparator = ""; 
}