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 恰好是一个 Tuple 类型的 List,而 Item1 是 StoreID。得到一个不同的列表后,它会遍历(非不同的)列表以获取每个适用的项目。效率低下是(大)内部列表为每个不同的项目(StoreID)重复迭代。

4

2 回答 2

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用于创建字符串。

于 2012-10-28T21:13:27.907 回答
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 = "";
}
于 2012-10-28T21:16:41.307 回答