根据列表的不同值迭代列表的有效方法是什么?

时间:2012-10-28 21:03:28

标签: c# linq

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)重复进行迭代。

2 个答案:

答案 0 :(得分: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 :(得分: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 = "";
}