I am trying to convert below nested for each loop into Linq. However I am still unable to do it successfully.
var objAct = new List<InformaticsBenchmarkSummary>();
foreach (var item in op)
{
foreach (var lstTp5 in lstTopFive)
{
if (item.UnitOfOperations.ContainsKey(lstTp5.SystemID))
{
var objIbm = new InformaticsBenchmarkSummary();
objIbm.CompanyId = item.CompanyId;
objIbm.CompanyName = item.CompanyName;
objIbm.LocationId = item.LocationId;
objIbm.LocationName = item.LocationName;
objIbm.UnitOfOperations.Add(lstTp5.SystemID,
item.UnitOfOperations[lstTp5.SystemID]);
objAct.Add(objIbm);
}
}
}
Where UnitOfOperations is of type Dictionary<int,string>();
op is again List<InformaticsBenchmarkSummary>()
lstTopFive is List<int>()
I tried, something like this but was unsuccessful syntactically
var output = from item in op
from lstTp5 in lstTopFive
where item.UnitOfOperations.ContainsKey(lstTp5.SystemID)
let v = new InformaticsBenchmarkSummary()
{
CompanyId = item.CompanyId,
CompanyName = item.CompanyName,
LocationId = item.LocationId,
LocationName = item.LocationName
}
.UnitOfOperations.Add(lstTp5.SystemID, item.UnitOfOperations[lstTp5.SystemID])
select v;
Nested loop works perfectly but I think, linq on this will increase performance.
Appreciate any help.
It is impossible in a Linq query-syntax to use the
UnitOfOperations.Addin the select. But you can do it using Method Chain and aSelectManymethod:If the property
UnitOfOperationshas a publicset, in this case, you can use the query-syntax.How do you replace 1
foreach? By afrom ... in ...Then, to replace 2
foreach, use 2from ... in ...But I doubt it will increase performance in such an operation.
Anyway, I don’t understand what you try to achieve. Because in all items of the output will have one and only one element in the dictionary
UnitOfOperations. Is it really what you want to do?UPDATE