Home > Back-end >  Combine LINQ and Foreach which in turn creates another list
Combine LINQ and Foreach which in turn creates another list

Time:12-27

I have the following piece of code which I am trying to improve:

var ApprovedAllowancesProductIds = from item in ApprovedAllowancesListFiltered select item.ProductId; //(1)

List<Product> productList = new List<Product>();
List<string> partitionProductKeys = new List<string>();

foreach (var item in ApprovedAllowancesProductIds)   //(2)
{
    string[] partitionKey = new string[] { CountryCD, item.ToString() };
    string PartitionKey = partitionKey.ConcatenatedStringWithPipeSeparator();
    partitionProductKeys.Add(PartitionKey);
}

var resultProduct = await _tableStorageService.FetchDataByMultiplePartitionKey<Product>(partitionProductKeys, QueryComparisonEnums.Equal);
productList.Add((Product)resultProduct);

For better performance I want to combine the functionality of (2) i.e., the entire foreach loop in (1). I saw some example as: Example1 and Example2 but they don't serve my purpose so please don't mark this as duplicate.

CodePudding user response:

you could combine with Select

var partitionProductKeys = ApprovedAllowancesProductIds
    .Select(item => 
    {
        string[] partitionKey = new string[] { CountryCD, item.ToString() };
        return partitionKey.ConcatenatedStringWithPipeSeparator();
    })
    .ToList();

you could apply the same concept with ApprovedAllowancesListFiltered if you want to merge the fist line as well with this code.

CodePudding user response:

I suggest you remove the outer list completely and loop on the objects instead of the property ProductId of the objects:

List<Product> productList = new List<Product>();
List<string> partitionProductKeys = new List<string>();
foreach (var item in ApprovedAllowancesListFiltered)
{
    string[] partitionKey = new string[] { CountryCD, item.ProductId.ToString() };
    string PartitionKey = partitionKey.ConcatenatedStringWithPipeSeparator();
    partitionProductKeys.Add(PartitionKey);
}
var resultProduct = await _tableStorageService.FetchDataByMultiplePartitionKey<Product>(partitionProductKeys, QueryComparisonEnums.Equal);
productList.Add((Product)resultProduct);

I hope this helps.

  • Related