patterncsharpMinor
Select Items from List using Array
Viewed 0 times
arraylistitemsusingselectfrom
Problem
Is there a better way to write this procedure?
public List GetInventory(int[] denominations)
{
var inventory = new List();
foreach (var denomination in denominations)
{
foreach (var item in Account)
{
if (item.Currency == denomination)
{
inventory.Add(item);
}
}
}
return inventory;
}Solution
You could use some linq to do this fairly easily. Converting the array to a HashSet will allow Contains to operate faster
This assumes that Account : IDenomination though, as does your original code. If that were not the case, you would use a
public List GetInventory(int[] denominations)
{
var denoms = new HashSet(denominations);
return Account.Where( a => denoms.Contains(a.Currency) ).ToList();
}This assumes that Account : IDenomination though, as does your original code. If that were not the case, you would use a
.Select() prior to .ToList() in order to select the IDenomination from Account.Code Snippets
public List<IDenomination> GetInventory(int[] denominations)
{
var denoms = new HashSet<int>(denominations);
return Account.Where( a => denoms.Contains(a.Currency) ).ToList();
}Context
StackExchange Code Review Q#82076, answer score: 7
Revisions (0)
No revisions yet.